DEV Community

Cover image for Best JavaScript One Liners that You Must Know
Shubh Sharma
Shubh Sharma

Posted on • Updated on

Best JavaScript One Liners that You Must Know

Introduction

JavaScript offers powerful techniques that can be used to to do very complex tasks in one line, these can be called one-liners. These are short lines of code that can perform complex tasks, making your code compact.

Especially while working with react I am using these one liners a lot.

So, Let's Start! 🚀🚀🚀

Ternary Operators Instead of If/Else

Instead of using If/else you can use ternary operators.

Condition is described before question mark ? and then we put true value and then : colon and then false value.

Example:

let variable = condition ? 'hello' : 'bye';
// if condition is true then hello is assigned to variable
// otherwise bye is assigned
Enter fullscreen mode Exit fullscreen mode
const age = 23;
let isAdult = age >= 18 ? "You're an adult" : "You're not an adult";
console.log(isAdult);
Enter fullscreen mode Exit fullscreen mode

You can even use it for if / else if / else conditions making more chained and complex decisions in easier and shorter code.

// example
const age = 23;
let isAdult = age >= 13  // if 
    ? "You are a teenager!"  // assign this 
    : age >= 18  // else if 
    ? "You are over 18!"  // assign this 
    : age >= 60 // else if 
    ? "You are old!" // assign this 
    : "You are a kid!" // else

console.log(isAdult);
Enter fullscreen mode Exit fullscreen mode

This is very much used in professional code when we want to execute something on the basis of some given conditions.

Printing values of an array

Instead of using a for loop we can use forEach() method with implicit return values.

const nums = [1, 2, 3, 4, 5, 6];
nums.forEach(num => console.log(num));
Enter fullscreen mode Exit fullscreen mode

Where num is each element of the array being printed on console.

Filtering out values from an array

In a single line of code you can use filter() method to filter out values of an array.

Filter method creates a new array of filtered out values.

const nums = [1, 2, 3, 4, 5, 6];
const filteredNums = nums.filter(num => num % 2 == 0);

console.log(filteredNums);
// output: 2, 4, 6
Enter fullscreen mode Exit fullscreen mode

Finding if a value exist or not in an array

const nums = [1,2,3,4,5]
const element = 19;

const isElementFound = nums.includes(element) ? "Yes" : "No"
console.log(isElementFound)
// output: No
// includes() returns boolean value: true/false
Enter fullscreen mode Exit fullscreen mode

This above code assigns No in the variable since there is no 19 value in the nums array.

Transforming an array using map

Map method can be used to transform existing values of an array and then return those values in form of new array.

const nums = [1,2,3,4];
const squaredNums = nums.map(num => num * num);
console.log(squaredNums);

// output: 1, 4, 9, 16
Enter fullscreen mode Exit fullscreen mode

"map() and filter() methods are the most used methods in react"

Getting the length of an array or string

const string = "Shubh"
const stringLen = string.length;
console.log(stringLen);

//output: 5
Enter fullscreen mode Exit fullscreen mode

Getting values out of an object

We use destructuring syntax to get out those values from the object.

const object = { 
  w: 0, 
  x: 1, 
  y: 2, 
  nestedObject: { 
      z: 3
  }
};

const { w, x, y, nestedObject: { z } } = object;

console.log(w);
console.log(x);
console.log(y);
console.log(z);

// output: 0 1 2 3
Enter fullscreen mode Exit fullscreen mode

Getting values out of arrays

We use destructuring syntax to get out those values from arrays.

const nestedArray = [1, 2, [3, 4], 5];

const [first, , [nested1, nested2], last] = nestedArray;

console.log(first);    // Output: 1
console.log(nested1);  // Output: 3
console.log(nested2);  // Output: 4
console.log(last);    // output: 5
Enter fullscreen mode Exit fullscreen mode

Here you can see that we didnt print 2 because we skipped it, yes we actually skipped it, look here ➡️ [first, ,

This extra comma means skip the value.

Swapping values using destructuring

let a = 10;
let b = 20;
[a, b] = [b, a];

console.log(a);    // output: 20
console.log(b);    // output: 10
Enter fullscreen mode Exit fullscreen mode

Explanation: "put value of b in a and value of a in b" ➡️ [a, b] = [b, a];

Spread Operator to merge, split and manipulate arrays and strings

const array1 = [1,2,3,4,5];
const array2 = [6,7,8];
const mergedArray = [...array1, ...array2];

console.log(mergedArray);    // output: 1,2,3,4,5,6,7,8
Enter fullscreen mode Exit fullscreen mode
// spliting values of a string using spread operator
const stringArray = [..."Shubh"];
console.log(stringArray);   // output: [ 'S', 'h', 'u', 'b', 'h' ]
Enter fullscreen mode Exit fullscreen mode
// rest operator
const [firstValue, secondValue, ...restValues] = [1,2,3,4,5];
console.log(restValues);    // output: [ 3, 4, 5 ]
Enter fullscreen mode Exit fullscreen mode

Finding min and max values of an array using Spread operator

const numbers = [2, 5, 1, 8];
const minNumber = Math.min(...numbers); // minNumber will be 1
const maxNumber = Math.max(...numbers); // maxNumber will be 8
Enter fullscreen mode Exit fullscreen mode

Default function parameters

function greet(name = "World") {
  console.log(`Hello ${name}!`);
}

greet();        // Output "Hello, World!"
greet("Shubh"); // Output "Hello, Shubh!"
Enter fullscreen mode Exit fullscreen mode

Conclusion

If you found this blog post helpful, please consider sharing it with others who might benefit. You can also follow me for more upcoming content on JavaScript, React, and other Web Development topics.

For paid collaboration, you can mail me at: gmail

Connect with me on Twitter, LinkedIn and GitHub

Thank you for Reading :)

Top comments (25)

Collapse
 
sreno77 profile image
Scott Reno

Please never use chaining in ternary operators because it's hard to follow and can lead to errors.

Collapse
 
anotherguy profile image
Igor Soloydenko

They are not more difficult to read than the 8f-else-if chains

Collapse
 
fastndead profile image
Umbetov Asman

Right off the bat the nested ternaries should be considered a crime

Collapse
 
anotherguy profile image
Igor Soloydenko

No, they shouldn't

Collapse
 
shubhsharma19 profile image
Shubh Sharma

Totally agree but its still a valid one liner in js :)

Collapse
 
joo_carlosrovedaostrov profile image
João Carlos Roveda Ostrovski

Can you elaborate please, i'm new to programming, and would love to know why.

Thank you.

Collapse
 
alexbodn profile image
abraham

the danger is precedence order of the operations in the ternary operator expression.
expressions should be put in parantheses.

Thread Thread
 
joo_carlosrovedaostrov profile image
João Carlos Roveda Ostrovski

Thank you!

Collapse
 
smits profile image
SmitS

might have to update your article. swapping values with const won't work... this could be misleading for someone starting fresh.

also I don't agree with the use of chaining ternary operator like others. but it could be just my perspective.

anyways, good luck!

Collapse
 
sthasam2 profile image
SthaSAM

That ternary chaining is absolutely horrible for readability.

Collapse
 
shubhsharma19 profile image
Shubh Sharma

Done Thanks a lot!

Collapse
 
debu0534 profile image
Debjyoti Banerjee • Edited

Swapping values using destructuring with const

🫣🥶

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)
const a = 10;
const b = 20;
[a, b] = [b, a];
Enter fullscreen mode Exit fullscreen mode

Did you even test that?

Collapse
 
itsjp profile image
Jaydeep Pipaliya

yes it works but the only thing that needs to change is let instead of const

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

That's my point... Not tested. Maybe even AI generated....

Collapse
 
emmanuelibikunle profile image
Emmanuel Ibikunle

No it doesn't
It would return a SyntaxError because a is already declared.

Collapse
 
shubhsharma19 profile image
Shubh Sharma • Edited

That was a mistake since i mostly use const while creating variables so yeah it was a habit of using const there, fixing it now, Thanks!

Collapse
 
alexbodn profile image
abraham

I don't that use const as much as I should :).
and prefer dynamic typing, for creativity.

Collapse
 
sthasam2 profile image
SthaSAM

If the dude doesn't know the difference between let and const, it's better to forgo the whole article, sadly.

Collapse
 
shubhsharma19 profile image
Shubh Sharma

It was a mistake! Fixing it now :)

Collapse
 
davvolun profile image
Dav • Edited

If you're a fresh coder right out of college or maybe a deep back-end dev who is just starting to mess with front end, and you ever give me a nested ternary like that in a pull request, I will come to your place, wherever you live, off-shore, domestic, doesn't matter, and I will punch you directly in the mouth.

Collapse
 
shubhsharma19 profile image
Shubh Sharma

in the face*

Collapse
 
alexbodn profile image
abraham

thank you Shubh, my friend.
your list is reconforting, and definitely good to know :).
about the chained ternary operations, precedence should be taken care of.

Collapse
 
designnotdrum profile image
Nick M.

You have to be trolling with the chained ternaries…. right? No one writes code like this in the real world.

Collapse
 
shubhsharma19 profile image
Shubh Sharma

I have seen that happen in react code while rendering multiple possible jsx code