JavaScript Shorthand Tips

JavaScript Shorthand Tips

1. Merge arrays

Normal writing :

We usually use the concat() method in Array to merge two arrays. The concat() method is used to merge two or more arrays. It does not change the existing arrays, but returns a new array. Let's take a look at a simple example:

let apples = ['🍎', '🍏'];
let fruits = ['πŸ‰', '🍊', 'πŸ‡'].concat(apples);

console.log( fruits );
//=> ["πŸ‰", "🍊", "πŸ‡", "🍎", "🍏"]

Shorthand method :

We can reduce the code by using the ES6 spread operator (...) as follows:

let apples = ['🍎', '🍏'];
let fruits = ['πŸ‰', '🍊', 'πŸ‡', ...apples]; // <-- here

console.log( fruits );
//=> ["πŸ‰", "🍊", "πŸ‡", "🍎", "🍏"]

The output obtained is the same as the normal writing method.

2. Merge arrays (at the beginning)

Normal writing :

Suppose we wanted to add all the items in the apples array to the beginning of the fruits array, rather than at the end as in the previous example. We can use

let apples = ['🍎', '🍏'];
let fruits = ['πŸ₯­', '🍌', 'πŸ’'];

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

console.log( fruits );
//=> ["🍎", "🍏", "πŸ₯­", "🍌", "πŸ’"]

Now red and green apples are merged at the beginning instead of at the end.

Shorthand method :

We can still shorten this long code using the ES6 spread operator (...) as follows:

let apples = ['🍎', '🍏'];
let fruits = [...apples, 'πŸ₯­', '🍌', 'πŸ’']; // <-- here

console.log( fruits );
//=> ["🍎", "🍏", "πŸ₯­", "🍌", "πŸ’"]

3. Cloning an Array

Normal writing :

We can easily clone an array using the slice() method in Array as follows:

let fruits = ['πŸ‰', '🍊', 'πŸ‡', '🍎'];
let cloneFruits = fruits.slice();

console.log( cloneFruits );
//=> ["πŸ‰", "🍊", "πŸ‡", "🍎"]

Shorthand method :

We can use the ES6 spread operator (...) to clone an array like this:

let fruits = ['πŸ‰', '🍊', 'πŸ‡', '🍎'];
let cloneFruits = [...fruits]; // <-- here

console.log( cloneFruits );
//=> ["πŸ‰", "🍊", "πŸ‡", "🍎"]

4. Destructuring assignment

Normal writing :

When working with arrays, we sometimes need to "unpack" an array into a bunch of variables, like this:

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

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

Shorthand method :

We can achieve the same result in one line of code using destructuring assignment:

let apples = ['🍎', '🍏'];
let [redApple, greenApple] = apples; // <-- here

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

5. Template Literals

Normal writing :

Normally, when we have to add an expression to a string, we do it like 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

Shorthand method :

With template literals, we can use backticks () so that we can wrap expressions in ${...}` and then embed them in strings, like this:

// Display name in between two strings
let name = 'Palash';
console.log(`Hello, ${name}!`); // <-- No need to use + var + anymore
//=> 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 Loop

Normal writing :

We can use a for loop to loop through an array like this:

let fruits = ['πŸ‰', '🍊', 'πŸ‡', '🍎'];

// Loop through each fruit
for (let index = 0; index < fruits.length; index++) { 
  console.log( fruits[index] ); // <-- get the fruit at current index
}

//=> πŸ‰
//=> 🍊
//=> πŸ‡
//=> 🍎

Shorthand method :

We can achieve the same result with much less code using a for...of statement as follows:

let fruits = ['πŸ‰', '🍊', 'πŸ‡', '🍎'];

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

//=> πŸ‰
//=> 🍊
//=> πŸ‡
//=> 🍎

7. Arrow Functions

Normal writing :

To iterate over an array, we can also use the forEach() method in Array. But it requires a lot of code to write, less than the most common for loop, but still a bit more than the for...of statement:

let fruits = ['πŸ‰', '🍊', 'πŸ‡', '🍎'];

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

//=> πŸ‰
//=> 🍊
//=> πŸ‡
//=> 🍎

Shorthand method :

But using arrow function expressions allows us to write the entire loop code in one line, like this:

let fruits = ['πŸ‰', '🍊', 'πŸ‡', '🍎'];
fruits.forEach(fruit => console.log( fruit )); // <-- Magic ✨

//=> πŸ‰
//=> 🍊
//=> πŸ‡
//=> 🍎

Most of the time I use the forEach loop with an arrow function. Here I show both the for...of statement and the forEach loop so that you can use the code according to your preferences.

8. Finding an object in an array

Normal writing :

To find an object from an array of objects by one of its properties, we usually use a for loop:

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 }

Shorthand method :

Wow! We wrote so much code above to implement this logic. But using the find() method in Array and the arrow function => allows us to do this in one line like this:

// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
  return arr.find(obj => obj.name === 'Apples'); // <-- here
}

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

9. Convert a string to an integer

Normal writing :

let num = parseInt("10")

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

Shorthand method :

We can achieve the same result by prefixing the string with + as follows:

let num = +"10";

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

10. Short-circuit evaluation

Normal writing :

If we have to set a value to not be falsy depending on another value, we usually use an if-else statement, 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"

Shorthand method :

But using short-circuit evaluation (||), we can do this in one line of code, like this:

function getUserRole(role) {
  return role || 'USER'; // <-- here
}

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

Basically, expression1 || expression2 is evaluated as a true expression. So, this means that if the first part is true, don't bother evaluating the rest of the expression.

A few additional points

Arrow Functions

If you don’t need the this context, the code can be even shorter when using arrow functions:

let fruits = ['πŸ‰', '🍊', 'πŸ‡', '🍎'];
fruits.forEach(console.log);

Finding an object in an array

You can use object destructuring and arrow functions to make the code more concise:

// 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 quote:

The reason code is our enemy is that many of us programmers write a lot of shitty code. If we can't get away with it, then it's best to do our best to keep the code simple.

If you love codingβ€”you really, really love codingβ€”the less you code, the more you love it.

This is the end of this article about JavaScript abbreviation skills. For more relevant JavaScript abbreviation content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Summary and usage tips of abbreviated syntax in JavaScript ES6
  • The most common abbreviation skills of JavaScript in history (recommended)
  • 12 common techniques for JavaScript abbreviations (can greatly reduce the amount of your JS code)
  • Summary of the 10 most commonly used code abbreviation techniques in JavaScript
  • 20 JS abbreviation skills to improve work efficiency

<<:  VMware vSphere6.0 server virtualization deployment and installation diagram (detailed steps)

>>:  PostgreSQL materialized view process analysis

Recommend

Data Structure - Tree (III): Multi-way Search Tree B-tree, B+ tree

Multi-way search tree Height of a complete binary...

Vue implements the product tab of the product details page function

This article example shares the specific code of ...

How to implement JavaScript output of Fibonacci sequence

Table of contents topic analyze Basic solution Ba...

Comprehensive understanding of Node event loop

Table of contents Node Event Loop Event loop diag...

Detailed example of using the distinct method in MySQL

A distinct Meaning: distinct is used to query the...

Docker image import, export, backup and migration operations

Export: docker save -o centos.tar centos:latest #...

Two ways to prohibit clearing the input text input cache in html

Most browsers will cache input values ​​by defaul...

Five ways to traverse JavaScript arrays

Table of contents 1. for loop: basic and simple 2...

JavaScript canvas to achieve code rain effect

This article shares the specific code for canvas ...

Two simple ways to remove text watermarks from web pages

<br /> When we browse certain websites and s...

How to encapsulate the table component of Vue Element

When encapsulating Vue components, I will still u...

The magic of tr command in counting the frequency of English words

We are all familiar with the tr command, which ca...

How to change apt-get source in Ubuntu 18.04

When using apt-get to install, it will be very sl...

A brief discussion on the solution of Tomcat garbled code and port occupation

Tomcat server is a free and open source Web appli...