DEV Community

Cover image for ๐Ÿค“7 Useful JavaScript One-Liner Code You Must Know ๐Ÿ’Ž
Random
Random

Posted on

๐Ÿค“7 Useful JavaScript One-Liner Code You Must Know ๐Ÿ’Ž

Hey Coders, it's me Md Taqui Imam. In today's blog, I want to share some 7 useful JavaScript one-liner code that can make your code look more professional and reduce code base size.


And Don't forget to checkout ๐Ÿ‘‡ once

Free HTML CSS Templates & Themes on HTMLrev

Free HTML CSS templates and themes for websites, landing pages, blogs, portfolios, ecommerce and admin dashboards

favicon htmlrev.com

So Let's begin and don't forget to drop a (๐Ÿ”ฅ๐Ÿ’–๐Ÿฆ„๐Ÿš€๐Ÿคฏ) and save it for later ๐Ÿ“Œ.

If you have any doubt then comment below ๐Ÿ’Œ.

Follow me on Githubโœ…


1. Find Value in Array ๐Ÿ”

Let's start with Basic One-Liner of how to Check if an Array contain a value or not.

// Array
const MyArray = [12,55,40,78,5];
// One-liner 
const haveValue = arr => arr.includes(5);
// Test
console.log("Answer ", haveValue(MyArray)) // Answer true

Enter fullscreen mode Exit fullscreen mode

This is the one-liner to see Array contain a Particular value or not. You can modify accourding to your needs.

2. Object Deep Clone ๐Ÿ’€

This one-Liner will make a Deep clone of your object:

const myObj = {
  "name": "Md Taqui Imam",
  "age": 22,
  "country": "india"
};

const deepClone = obj => JSON.parse(JSON.stringify(obj));

console.log("Answer ", deepClone(myObj));

// Answer Object {"name": "Md Taqui Imam","age": 22,"country": "india"}
Enter fullscreen mode Exit fullscreen mode

And thanks to @jonrandy contribuiting about one more shortest and easier way to clone objects in javascript with structuredClone( )

const myObj = {
  "name": "Md Taqui Imam",
  "age": 22,
  "country": "india"
};

const deepClone = structuredClone(myObj) // with  structuredClone

console.log("Answer ", deepClone);

Enter fullscreen mode Exit fullscreen mode

3. Scroll To Top ๐Ÿ“ƒ

This is the One-Liner that instantly navigates you to the Top of the Page :

window.scrollTo(0, 0) // navigate to Top
Enter fullscreen mode Exit fullscreen mode

4. Truncate a String To a Specific Length "..."โญ

This One-Liner is to Truncate a String and add "..." to an End on a specific given Length :

const myString = "Lorem ipsum is simply dummy text of the printing and typesetting industry.";

const truncate = (str, len) => str?.length > len ? str.slice(0, len) + "..." : str;

console.log("Answer", truncate(myString, 52)); 
// Answer Lorem ipsum is simply dummy text of the printing and...
Enter fullscreen mode Exit fullscreen mode

5. Remove Duplicated item in ๐Ÿ‘‰ [ ]

This one-Liner will return a new Array without repeating duplicated item from an Array :

const myArr = [4,8,3,9,4];

const duplicate = arr => [...new Set(arr)]

console.log("Answer ", duplicate(myArr));

 // Answer (4) [4, 8, 3, 9]
Enter fullscreen mode Exit fullscreen mode

6. Check all are same ๐Ÿค” or not

This one-liner will help you to check that all item of an Array are same/identical or Not :

const myArr = [4,4,4,4,4];

const allSame = arr => arr.every(val => val === arr[0]);

console.log("Answer ", allSame(myArr));

 // Answer true
Enter fullscreen mode Exit fullscreen mode

7. Get last item from ๐Ÿ‘‰ [ ]

Now, Last one-liner will help you to get the last item of an array :

const myArr = [4,8,2,9,1,6];

const lastItm = arr => arr[arr.length - 1];

console.log("Answer", lastItm(myArr));

 // Answer 6
Enter fullscreen mode Exit fullscreen mode

See you in next week ๐Ÿ˜…

I hope you find this Blog post helpful and these 7 one-liners will help you to make your code base size smaller, and boost you productivity.

Have a nice day๐Ÿ‘‹

github

twitter

portfolio

buymeacoffee

Top comments (13)

Collapse
ย 
ranjancse profile image
Ranjan Dailata โ€ข โ€ข Edited

Improved code for deep cloning of objects.

function deepClone(obj) {
  // Check if the input is an object
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  return JSON.parse(JSON.stringify(obj));
}
Enter fullscreen mode Exit fullscreen mode
Collapse
ย 
random_ti profile image
Random โ€ข

Thankyou Ranjan for your contribuition ๐Ÿ™

Collapse
ย 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ โ€ข

Further improved code - use the native structuredClone:

const clone = structuredClone(obj)
Enter fullscreen mode Exit fullscreen mode

Faster, less problems, more options.

Thread Thread
ย 
random_ti profile image
Random โ€ข

this is ๐Ÿ”ฅ

Collapse
ย 
joolsmcfly profile image
Julien Dephix โ€ข

Hi.

You can add js next to the opening backticks to have syntax highlight.

Also note that JSON.stringify will work as you'd expect if properties are booleans, numbers etc. Functions, Maps, Sets will be omitted or null'd.

Check the doc for more info.

Collapse
ย 
random_ti profile image
Random โ€ข

Thankyou so much julien, i really don't know about this js syntax feature of dev to.

Collapse
ย 
joolsmcfly profile image
Julien Dephix โ€ข โ€ข Edited

It can be any supported language too.

<p class="greeting">Hello from HTML</p>
Enter fullscreen mode Exit fullscreen mode
echo "Hello from PHP";
Enter fullscreen mode Exit fullscreen mode

etc

Collapse
ย 
jeffchavez_dev profile image
Jeff Chavez โ€ข

Thank you. For #5, Is it dublicate or duplicate?

Collapse
ย 
random_ti profile image
Random โ€ข

Sorry its duplicate ๐Ÿ˜… Thankyou for informing me

Collapse
ย 
jeffchavez_dev profile image
Jeff Chavez โ€ข

You're welcome

Collapse
ย 
devluc profile image
Lucian Devluc โ€ข

Awesome tips Taqui, thanks for sharing them

Collapse
ย 
milanx profile image
Milan Mohapatra โ€ข

Looking cool๐Ÿ”ฅ, how can I add buttons and follow me sections like you.

Collapse
ย 
random_ti profile image
Random โ€ข โ€ข Edited

It is called CTA(call to action) button.

This is the syntax to add CTA ๐Ÿ‘‡ Button

{% cta https://example.com %} Follow me in Githubโœ…{% endcta %}
Enter fullscreen mode Exit fullscreen mode

Replace "example.com" and "Follow me in Github" accourding to you.

๐Ÿ˜Š