10 Awesome JavaScript Shorthand Tricks

1. Merge arrays


Ordinary writing:

We usually merge two arrays using the concat() method in Array. Using the concat() method to merge two or more arrays does not change the existing arrays, but returns a new array.
Shorthand:

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

2. Merge arrays (at the beginning)


Normal writing: Suppose we want to add all items in the apples array to the beginning of the Fruits array, not at the end as in the previous example. We can use Array.prototype.unshift() to do this.
Shorthand:

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

3. Clone the array


Ordinary writing:

We can easily clone an array using slice() method in Array
Shorthand:

We can clone an array like this using the ES6 spread operator (...)

4. Destructuring assignment


Ordinary writing:

When working with arrays, we sometimes need to "unpack" the array into a bunch of variables.
Shorthand:

We can achieve the same result in one line of code by destructuring assignment.

5. Template literals


Ordinary 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


Shorthand:
With template literals, we can use backticks (``), so that we can wrap expressions in ${…}` and then embed them into 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


Ordinary writing:
We can loop through an array using a for loop 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:
We can achieve the same result with much less code using the for...of statement as follows:
let fruits = ['🍉', '🍊', '🍇', '🍎'];

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

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


7. Arrow functions


Ordinary writing:
To iterate over an array, we can also use the forEach() method from Array. But it takes a lot of code to write, although less than the most common for loop, but still a little more than a for...of statement:
let fruits = ['🍉', '🍊', '🍇', '🍎'];

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

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


Shorthand:
But using arrow function expressions allows us to write a complete loop of code in one line, like this:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(fruit => console.log(fruit )); // <-- Magic ✨

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


8. Find Objects in Arrays


Ordinary 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 the 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:
Above we wrote so much code to implement this logic. But using the find() method and arrow function => in Array allows us to do it 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 String to Integer


Ordinary writing:
The parseInt() function is used to parse strings and return integers:
let num = parseInt("10")

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


Shorthand:
We can achieve the same result by prefixing the string with +, like this:
let num = +"10";

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


10. Short-circuit evaluation


Ordinary writing:
If we have to set a value that is not falsy based on another value, an if-else statement is usually used, 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:
But using short-circuit evaluation (||), we can do this with one line of code, like this:
function getUserRole(role) {
return role || 'USER'; // <-- here
}

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


add a few points
Arrow function:
If you don't need the this context, the code can also be shorter when using arrow functions:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(console.log);


Find an object in an array:
You can use object destructuring and arrow functions to make your code leaner:
// 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 alternative:
const getUserRole1 = (role = "USER") => role;
const getUserRole2 = role => role ?? "USER";
const getUserRole3 = role => role ? role : "USER";


coding habits
Finally, I want to talk about coding habits. Code conventions abound, but few are strictly adhered to. The reason is that before the code specification is formulated, you already have your own set of coding habits, and it is difficult to change your habits in a short time. Good coding habits can lay the foundation for subsequent growth. Below, list some of the benefits of development specifications, so that everyone understands the importance of code specifications:

Canonical code promotes teamwork.
Canonical code can reduce bug handling.
Canonical code can reduce maintenance costs.
Canonical code facilitates code review.
Cultivate the habit of code specification, which helps the programmer's own growth.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00