Best JavaScript One Liners that You Must Know

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
const age = 23;
let isAdult = age >= 18 ? "You're an adult" : "You're not an adult";
console.log(isAdult);

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

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

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

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

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

"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

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

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

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

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

console.log(a);    // output: 20
console.log(b);    // output: 10

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
// spliting values of a string using spread operator
const stringArray = [..."Shubh"];
console.log(stringArray);   // output: [ 'S', 'h', 'u', 'b', 'h' ]
// rest operator
const [firstValue, secondValue, ...restValues] = [1,2,3,4,5];
console.log(restValues);    // output: [ 3, 4, 5 ]

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

Default function parameters

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

greet();        // Output "Hello, World!"
greet("Shubh"); // Output "Hello, Shubh!"

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

Did you find this article valuable?

Support Shubh's Blog ☕ by becoming a sponsor. Any amount is appreciated!