DEV Community

Cover image for 8 Best JavaScript One-Liners
Shivam Singh
Shivam Singh

Posted on

8 Best JavaScript One-Liners

Hey everyone! If you're new to coding, you're probably excited but maybe a little overwhelmed, right? Don't sweat it! ๐Ÿ˜… Today, we're going to look at some really simple but super cool one-liners in JavaScript. These are short lines of code that do something awesome, and they'll save you time and impress your friends. So, grab your favorite snack and let's jump into the magical world of easy-peasy JavaScript tricks!


1๏ธโƒฃ Picking a Random Element from an Array

How about some unpredictability in your life? Let's get a random element from an array:

// Input: [1, 2, 3, 4]
const randomElement = arr => arr[Math.floor(Math.random() * arr.length)];
// Output: Something like 2, or 4, or 1...you get it.
Enter fullscreen mode Exit fullscreen mode

In the coding world, this is like asking your bartender for a "surprise me" and hoping you don't get Tabasco sauce in your martini. ๐Ÿธ You never know what you're gonna get, kinda like life!


2๏ธโƒฃ Getting Rid of Duplicate Array Elements

If your array sparks no joy because itโ€™s cluttered with duplicates, clean it up with:

// Input: [1, 2, 2, 3]
const uniqueArray = [...new Set([1, 2, 2, 3])];
// Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Look at that! Your array is now tidier than a hipster's beard on a Saturday night. โœ‚๏ธ Goodbye, duplicates! Sayonara, clutter!


3๏ธโƒฃ Sorting Array Objects by a Specific Property

Ever wished your objects knew their place? Teach 'em some manners:

// Input: 'name', [{name:'Bob', age:25}, {name:'Alice', age:22}]
const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : -1);
// Output: [{name:'Alice', age:22}, {name:'Bob', age:25}]
Enter fullscreen mode Exit fullscreen mode

Voilร ! Your objects are now in a straight line, behaving better than kids on a sugar rush. ๐Ÿญ Priorities, people!


4๏ธโƒฃ Checking if Two Arrays or Objects Are Equal

Are these two things really the same? Time for some self-reflection:

// Input: [1, 2], [1, 2]
const arraysEqual = JSON.stringify([1, 2]) === JSON.stringify([1, 2]);
// Output: true
Enter fullscreen mode Exit fullscreen mode

There you have it. As identical as two peas in a pod or the Kardashians before they discovered contouring. ๐Ÿ’„


5๏ธโƒฃ Make Your Code Wait for a Specific Time

Sometimes we all need to take a breather. Make your code chill out for a sec:

const chill = ms => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
  console.log("Before waiting");
  await chill(2000);
  console.log("After waiting for 2 seconds");
})();
Enter fullscreen mode Exit fullscreen mode

Itโ€™s like your code took a short vacation. Now it's back, refreshed and ready to rock! ๐Ÿ–๏ธ


6๏ธโƒฃ Extract a Property from an Array of Objects

Need to grab a specific property from an array of objects? Cherry-pick it!

const pluck = (arr, key) => arr.map(obj => obj[key]);
console.log(pluck([{x: 1}, {x: 2}], 'x')); // Output: [1, 2]
Enter fullscreen mode Exit fullscreen mode

Your code is now as selective as a toddler deciding which vegetable to fling across the room. ๐Ÿฅฆ


7๏ธโƒฃ Inserting an Element at a Specific Position

Why wait your turn? Insert an element wherever you like:

// Input: [1, 2, 4]
const insert = (arr, index, newItem, a=[...arr]) => (a.splice(index, 0, newItem),a);
// Output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Smooth! That element snuck into the array like a teenager sneaking into an R-rated movie. ๐ŸŽฌ


8๏ธโƒฃ Generate a Random Hexadecimal Color Code

Need a random color? Say no more:

// Input: No input needed
const randomColor = "#" + (~~(Math.random() * 8**8)).toString(16).padStart(6,0);
// Output: Something like #f5a623
Enter fullscreen mode Exit fullscreen mode

Tada! Your screen now looks like a unicorn sneezed on it. Beautiful! ๐ŸŒˆ


Conclusion: Over to You, Superstar! ๐ŸŒŸ

Wow, what a ride! ๐ŸŽข We just covered 8 simple but handy shortcuts in JavaScript. These one-liners are like little toolkits ๐Ÿ› ๏ธ that help you do awesome stuff without breaking a sweat. Got any cool shortcuts or tricks youโ€™ve learned and want to share? We're all ears! Drop them in the comments section below. Happy coding, and remember, the best code is the one that makes you smile! ๐Ÿ˜Š

Happy coding, and remember, always keep it sassy and classy! ๐Ÿธ๐ŸŽ‰

Top comments (26)

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

3) can be shorter:

const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] || -1)
Enter fullscreen mode Exit fullscreen mode

5) You have not shown how to use the function, and it will only delay the execution of code chained with the Promise. Statements immediately after will proceed as normal with no delay.

6) Your input is missing the key.

7) Your input shown is wrong, and this can also be shorter - using the built-in method designed for the purpose:

const insert = (arr, index, newItem, a=[...arr]) => (a.splice(index, 0, newItem), a)
Enter fullscreen mode Exit fullscreen mode

8) Will not function correctly as it will never return #ffffff, and also many other colours as you are not padding the string with leading zeroes. A correct version:

const randomColor = "#" + (~~(Math.random() * 8**8)).toString(16).padStart(6,0)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
skyjur profile image
Ski • Edited

#3: when sorting numbers just use subtraction for numbers just do a - b for ascending order

arr.sort((a, b) => a[key] - b[key])
Enter fullscreen mode Exit fullscreen mode

and for strings use a.localeCompare(b)

Collapse
 
shivams1007 profile image
Shivam Singh

Yes, this is also correct!

Collapse
 
shivams1007 profile image
Shivam Singh

1. The chill Function

You're correct; my initial example did not show how to actually use the function in a meaningful way. It's a Promise-based function, so you'd typically use it with async/await or .then() to actually cause a delay in the code's execution. Here's how you could use it:

(async () => {
  console.log("Before waiting");
  await chill(2000);
  console.log("After waiting for 2 seconds");
})();
Enter fullscreen mode Exit fullscreen mode

2. The sortBy Function

You bring up a good point. The function could indeed be simplified to:

const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : -1);
Enter fullscreen mode Exit fullscreen mode

This approach assumes that a[key] and b[key] will never be equal if sorting is based on unique identifiers, which might be okay for some cases but not all.

3. The pluck Function

You're right; the input was incomplete without specifying the key. A more full example could be:

const pluck = (arr, key) => arr.map(obj => obj[key]);
console.log(pluck([{x: 1}, {x: 2}], 'x')); // Output: [1, 2]
Enter fullscreen mode Exit fullscreen mode

4. The insert Function

Your point is valid; the input example could have been more complete. Also, your shorter version using splice is more concise. However, one benefit of the original slice approach is that it does not mutate the original array.

const insert = (arr, index, newItem, a=[...arr]) => (a.splice(index, 0, newItem),a);
Enter fullscreen mode Exit fullscreen mode

5. The randomColor Function

You are correct again; the original version can indeed skip some colors and never reach #FFFFFF. Your version with padding zeros is more accurate in generating the full spectrum of colors:

const randomColor = "#" + (~~(Math.random() * 8**8)).toString(16).padStart(6,0);
Enter fullscreen mode Exit fullscreen mode

Thank you for pointing out these details; your observations are insightful and enhance the accuracy and efficiency of the examples.
I will update it according to it!

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

Try the shorter sortBy with repeated identifiers. Works just fine. If the two identifiers are equal it makes no difference what order they are sorted in.

My splice example doesn't mutate the original array.

Thread Thread
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ

Might want to fix the glaring typo in the header image too! ๐Ÿ˜‰

Thread Thread
 
shivams1007 profile image
Shivam Singh

@jonrandy which one?

Thread Thread
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ

"8 One-Linear You Will Love"

Thread Thread
 
shivams1007 profile image
Shivam Singh • Edited

ohh yes you are correct! ๐Ÿ˜Š
I am open for any other suggestions

Collapse
 
shivams1007 profile image
Shivam Singh

1. The sortBy Function with Repeated Identifiers

You're right that if two elements have the same identifier, the order doesn't matter for those particular elements. In many sorting algorithms, including JavaScript's native .sort(), elements that compare as equal remain in their original order (stable sort). So, your simplified version is equally effective:

const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : -1);
Enter fullscreen mode Exit fullscreen mode

This will work just fine even with repeated identifiers.

2. The splice Example and Array Mutation

I apologize for the misunderstanding. You're correct; your example using splice actually doesn't mutate the original array because you made a shallow copy (a=[...arr]) before applying the splice.

Here's the function for clarity:

const insert = (arr, index, newItem, a=[...arr]) => (a.splice(index, 0, newItem),a);
Enter fullscreen mode Exit fullscreen mode

In this function, a=[...arr] creates a new array that is a copy of the original arr. Then, splice is called on this new array (a), so the original arr remains unchanged. Therefore, it is a non-mutating operation on the original array.

Thank you for your keen observations; they serve to improve the quality and accuracy of the discussion.

Collapse
 
dannyengelman profile image
Danny Engelman

My favorite oneliner when building Web Components, or any DOM is:

const element=(t,p={})=>Object.assign(document.createElement(t), p);
Enter fullscreen mode Exit fullscreen mode

Click the Result tab:

Collapse
 
shivams1007 profile image
Shivam Singh

Great!

Collapse
 
skyjur profile image
Ski • Edited

Please never do #4: comparing using JSON.stringify(a) == JSON.stringify(b). It's very poor practice: it doesn't guarantee correctness - in some cases it can give false positive as well as false negative (for instance objects equal but key order is not JSON stringify will produce different output) - as some objects might not get stringified at all, and some values can even result into json.stringify throwing an error.

If you have class objects, then good idea is to implement equal() method on your object and compare a.equal(b). For generic object use recursive algorithm.

But more importantly consider why do you need deep equality check in first place - as it can be computationally intensive. Likely there should be ways to avoid it in first place.

Collapse
 
shivams1007 profile image
Shivam Singh

Yes it doesn't give a correct solution for every scenario

Collapse
 
webjose profile image
Josรฉ Pablo Ramรญrez Vargas

While I'm not saying that all of these suffer from it, this is the kind of programming that leads to performance hell. People get so used to shorthand versions of things (mostly loop-based), that end up enumerating collections an enormously unnecessary amount of times.

This is also found in .Net and the LINQ advocates.

Bottom line: Shorter is more commonly worse than you think. Analyze your algorithms thoroughly.

Collapse
 
shivams1007 profile image
Shivam Singh • Edited

It's not totally correct. It depends

Collapse
 
lucasm4sco profile image
Lucas

Great, I think it would be useful to also comment that it can happen that objects with the same values โ€‹โ€‹still return false when compared with stringify method due to the order of their properties

Collapse
 
shivams1007 profile image
Shivam Singh

yes correct!

Collapse
 
jamesgj5 profile image
James Graรงa-Jones

Thanks for the article, I definitely learnt a lot from this! I slightly worry that some of the wording in Point 4 distracts the reader from realising that just because two arrays have the same values doesn't mean they actually are the same. They aren't the same object, for example, they just have the same values in them. Fun article though :)

Collapse
 
shivams1007 profile image
Shivam Singh

thanks

Collapse
 
arielmejiadev profile image
Ariel Mejia

Hi @shivamblog If it makes sense to you I would add a one-liner to shuffle and pick items from an array:

const randomizeArray = () => [...array].sort(() => 0.5 - Math.random()).slice(0, items);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shivams1007 profile image
Shivam Singh

what is items here?

Collapse
 
arielmejiadev profile image
Ariel Mejia

@shivamblog Sorry items could be the number of items so you can shuffle and also get only some of them:

and the array should be the array to shuffle and slice it.

const randomizeArray = () => [...array].sort(() => 0.5 - Math.random()).slice(0, numberOfItems);
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
shivams1007 profile image
Shivam Singh

Then it is correct!

Collapse
 
tobiasss97 profile image
Tobiasss97

Great post

Collapse
 
shivams1007 profile image
Shivam Singh

thanks!