Best JavaScript One Liners that You Must Know
Shubh Sharma

Shubh Sharma @shubhsharma19

About: Self taught web developer and designer

Location:
India
Joined:
Oct 28, 2021

Best JavaScript One Liners that You Must Know

Publish Date: May 21 '24
52 25

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 :)

Comments 25 total

  • Scott Reno
    Scott RenoMay 21, 2024

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

    • Igor Soloydenko
      Igor SoloydenkoMay 28, 2024

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

  • Umbetov Asman
    Umbetov AsmanMay 21, 2024

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

  • Red Ochsenbein (he/him)
    Red Ochsenbein (he/him)May 21, 2024
    const a = 10;
    const b = 20;
    [a, b] = [b, a];
    
    Enter fullscreen mode Exit fullscreen mode

    Did you even test that?

    • Jaydeep Pipaliya
      Jaydeep PipaliyaMay 22, 2024

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

    • SthaSAM
      SthaSAMMay 24, 2024

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

    • Shubh Sharma
      Shubh SharmaMay 25, 2024

      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!

      • abraham
        abrahamMay 30, 2024

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

  • Debjyoti Banerjee
    Debjyoti BanerjeeMay 22, 2024

    Swapping values using destructuring with const

    🫣🥶

  • SDevr
    SDevrMay 23, 2024

    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!

    • SthaSAM
      SthaSAMMay 24, 2024

      That ternary chaining is absolutely horrible for readability.

    • Shubh Sharma
      Shubh SharmaMay 25, 2024

      Done Thanks a lot!

  • Dav
    DavMay 24, 2024

    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.

  • Nick M.
    Nick M.May 24, 2024

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

    • Shubh Sharma
      Shubh SharmaMay 25, 2024

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

  • abraham
    abrahamMay 30, 2024

    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.

Add comment