10 great JavaScript shorthand skills

Time:2022-1-12

Today I want to share 10 great JavaScript shorthand methods that can speed up development and get twice the result with half the effort.

Let’s go!

1. Merge arrays

Common writing:

We usually useArrayMediumconcat()Method to merge two arrays. useconcat()Method to merge two or more arrays. Instead of changing the existing array, it returns a new array. Take a simple example:

let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇'].concat(apples);

console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]

Abbreviation:

We can extend the operator by using ES6(...)To reduce the code, as follows:

let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples];  //  ["🍉", "🍊", "🍇", "🍎", "🍏"]

The output obtained is the same as that in normal writing.

2. Merge arrays (at the beginning)

Common writing:

Suppose we want toapplesAll items in the array are added to theFruitsThe beginning of the array, not the end, as in the previous example. We can useArray.prototype.unshift()To do this:

let apples = ['🍎', '🍏'];
let fruits = ['🥭', '🍌', '🍒'];

// Add all items from apples onto fruits at start
Array.prototype.unshift.apply(fruits, apples)

console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]

Now the red and green apples will merge at the beginning, not at the end.

Abbreviation:

We can still use the ES6 extension operator(...)Shorten this long code as follows:

let apples = ['🍎', '🍏'];
let fruits = [...apples, '🥭', '🍌', '🍒'];  //  ["🍎", "🍏", "🥭", "🍌", "🍒"]

3. Clone array

Common writing:

We can useArrayMediumslice()Method to easily clone an array, as follows:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = fruits.slice();

console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]

Abbreviation:

We can use the ES6 extension operator(...)Clone an array like this:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = [...fruits];  //  ["🍉", "🍊", "🍇", "🍎"]

4. Deconstruction assignment

Common writing:

When processing arrays, we sometimes need to unpack the array into a pile of variables, as shown below:

let apples = ['🍎', '🍏'];
let redApple = apples[0];
let greenApple = apples[1];

console.log( redApple );    //=> 🍎
console.log( greenApple );  //=> 🍏

Abbreviation:

We can achieve the same result with one line of code by deconstructing the assignment:

let apples = ['🍎', '🍏'];
let [redApple, greenApple] = apples;  //  🍎
console.log( greenApple );  //=> 🍏

5. Template literal quantity

Common writing:

Usually, when we have to add an expression to a string, we do this:

// Display name in between two strings
let name = 'Palash';
console.log('Hello, ' + name + '!');
//=> Hello, Palash!

// Add & Subtract two numbers
let num1 = 20;
let num2 = 10;
console.log('Sum = ' + (num1 + num2) + ' and Subtract = ' + (num1 - num2));
//=> Sum = 30 and Subtract = 10

Abbreviation:

With template literals, we can use backquotes()So we can wrap the expression in${…}` , and then embedded into the string, as follows:

// Display name in between two strings
let name = 'Palash';
console.log(`Hello, ${name}!`);  //  Hello, Palash!

// Add two numbers
let num1 = 20;
let num2 = 10;
console.log(`Sum = ${num1 + num2} and Subtract = ${num1 - num2}`);
//=> Sum = 30 and Subtract = 10

6. For cycle

Common writing:

We can useforLoop loops through an array like this:

let fruits = ['🍉', '🍊', '🍇', '🍎'];

// Loop through each fruit
for (let index = 0; index < fruits.length; index++) { 
  console.log( fruits[index] );  //  🍉
//=> 🍊
//=> 🍇
//=> 🍎

Abbreviation:

We can usefor...ofStatement achieves the same result with much less code, as follows:

let fruits = ['🍉', '🍊', '🍇', '🍎'];

// Using for...of statement 
for (let fruit of fruits) {
  console.log( fruit );
}

//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

7. Arrow function

Common writing:

To traverse the array, we can also useArrayMediumforEach()method. But you need to write a lot of code, although more than the most commonforFewer cycles, but still better thanfor...ofMore statements:

let fruits = ['🍉', '🍊', '🍇', '🍎'];

// Using forEach method
fruits.forEach(function(fruit){
  console.log( fruit );
});

//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

Abbreviation:

However, using the arrow function expression allows us to write the complete loop code in one line, as follows:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(fruit => console.log( fruit ));  //  🍉
//=> 🍊
//=> 🍇
//=> 🍎

Most of the time I use functions with arrowsforEachLoop, here I putfor...ofStatement andforEachLoops are displayed to facilitate everyone to use the code according to their preferences.

8. Find objects in the array

Common writing:

To find an object from an object array through one of the properties, we usually useforCycle:

let inventory = [
  {name: 'Bananas', quantity: 5},
  {name: 'Apples', quantity: 10},
  {name: 'Grapes', quantity: 2}
];

// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
  for (let index = 0; index < arr.length; index++) {

    // Check the value of this object property `name` is same as 'Apples'
    if (arr[index].name === 'Apples') {  //=> 🍎

      // A match was found, return this object
      return arr[index];
    }
  }
}

let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }

Abbreviation:

WOW! We have written so much code to implement this logic. But useArrayMediumfind()Methods and arrow functions=>, let’s do it like this:

// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
  return arr.find(obj => obj.name === 'Apples');  //  { name: "Apples", quantity: 10 }

9. Convert string to integer

Common writing:

parseInt()The function parses a string and returns an integer:

let num = parseInt("10")

console.log( num )         //=> 10
console.log( typeof num )  //=> "number"

Abbreviation:

We can add+Prefix to achieve the same result, as follows:

let num = +"10";

console.log( num )           //=> 10
console.log( typeof num )    //=> "number"
console.log( +"10" === 10 )  //=> true

10. Short circuit evaluation

Common writing:

If we have to set a value according to another value, which is not a false value, it is generally usedif-elseStatement, like this:

function getUserRole(role) {
  let userRole;

  // If role is not falsy value
  // set `userRole` as passed `role` value
  if (role) {
    userRole = role;
  } else {

    // else set the `userRole` as USER
    userRole = 'USER';
  }

  return userRole;
}

console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"

Abbreviation:

However, short circuit evaluation is used(||), we can do this in one line of code as follows:

function getUserRole(role) {
  return role || 'USER';  //  "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"

Basically,expression1 || expression2Evaluated asreallyexpression. Therefore, this means that if the first part is true, you don’t have to bother evaluating the rest of the expression.

Some additional points

Arrow function

If you don’t needthisContext, the code can also be shorter when using the arrow function:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(console.log);

Find objects in array

You can use object deconstruction and arrow functions to streamline your code:

// Get the object with the name `Apples` inside the array
const getApples = array => array.find(({ name }) => name === "Apples");

let result = getApples(inventory);
console.log(result);
//=> { name: "Apples", quantity: 10 }

Short circuit evaluation alternatives

const getUserRole1 = (role = "USER") => role;
const getUserRole2 = role => role ?? "USER";
const getUserRole3 = role => role ? role : "USER";

Finally, I would like to end with a paragraph:

Code is our enemy because many of our programmers write a lot of shit code. If we can’t get rid of it, we’d better try our best to keep the code simple.

If you like writing code – really, really like writing code – the less code you write, the deeper your love.

Welcome to my official account: front-end new world.
Only focus on front-end technology and share JS / CSS technology tutorials every day; Front end development components such as Vue, react and jquery

image