DEV Community

Cover image for 10 Awesome JavaScript Shorthands
Palash Mondal
Palash Mondal

Posted on • Updated on • Originally published at iampalash.hashnode.dev

10 Awesome JavaScript Shorthands

Hi everyone ๐Ÿ‘‹

Today I wanted to share with you 10 awesome JavaScript shorthands that will increase your speed by helping you to write less code and do more.

Let's start!

1. Merge Arrays

Longhand:

We usually merge two arrays using Array concat() method. The concat() method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array. Here is a simple example:

let apples = ['๐ŸŽ', '๐Ÿ'];
let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡'].concat(apples);

console.log( fruits );
//=> ["๐Ÿ‰", "๐ŸŠ", "๐Ÿ‡", "๐ŸŽ", "๐Ÿ"]
Enter fullscreen mode Exit fullscreen mode

Shorthand:

We can shorten this a bit by using ES6 Spread Operator (...) like this:

let apples = ['๐ŸŽ', '๐Ÿ'];
let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', ...apples];  // <-- here

console.log( fruits );
//=> ["๐Ÿ‰", "๐ŸŠ", "๐Ÿ‡", "๐ŸŽ", "๐Ÿ"]
Enter fullscreen mode Exit fullscreen mode

and we are still getting the same output as before. ๐Ÿ˜ƒ


2. Merge Arrays (but at the start)

Longhand:

Let's say we want to add all the items from the apples array at the start of fruits array, instead of at the end like we have seen in the last example. We can do this using Array.prototype.unshift() like this:

let apples = ['๐ŸŽ', '๐Ÿ'];
let fruits = ['๐Ÿฅญ', '๐ŸŒ', '๐Ÿ’'];

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

console.log( fruits );
//=> ["๐ŸŽ", "๐Ÿ", "๐Ÿฅญ", "๐ŸŒ", "๐Ÿ’"]
Enter fullscreen mode Exit fullscreen mode

Now the two red & green apples are at the start instead of the end after merging.

Shorthand:

We can shorten this long code again using ES6 Spread Operator (...) like this:

let apples = ['๐ŸŽ', '๐Ÿ'];
let fruits = [...apples, '๐Ÿฅญ', '๐ŸŒ', '๐Ÿ’'];  // <-- here

console.log( fruits );
//=> ["๐ŸŽ", "๐Ÿ", "๐Ÿฅญ", "๐ŸŒ", "๐Ÿ’"]
Enter fullscreen mode Exit fullscreen mode

3. Clone Array

Longhand:

We can easily clone an array using the Array slice() method like this:

let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', '๐ŸŽ'];
let cloneFruits = fruits.slice();

console.log( cloneFruits );
//=> ["๐Ÿ‰", "๐ŸŠ", "๐Ÿ‡", "๐ŸŽ"]
Enter fullscreen mode Exit fullscreen mode

Shorthand:

Using ES6 Spread Operator (...) we can clone an array like this:

let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', '๐ŸŽ'];
let cloneFruits = [...fruits];  // <-- here

console.log( cloneFruits );
//=> ["๐Ÿ‰", "๐ŸŠ", "๐Ÿ‡", "๐ŸŽ"]
Enter fullscreen mode Exit fullscreen mode

4. Destructuring Assignment

Longhand:

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

let apples = ['๐ŸŽ', '๐Ÿ'];
let redApple = apples[0];
let greenApple = apples[1];

console.log( redApple );    //=> ๐ŸŽ
console.log( greenApple );  //=> ๐Ÿ
Enter fullscreen mode Exit fullscreen mode

Shorthand:

We can achieve the same result in a single line using Destructuring assignment like this:

let apples = ['๐ŸŽ', '๐Ÿ'];
let [redApple, greenApple] = apples;  // <-- here

console.log( redApple );    //=> ๐ŸŽ
console.log( greenApple );  //=> ๐Ÿ
Enter fullscreen mode Exit fullscreen mode

5. Template literals

Longhand:

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

// 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
Enter fullscreen mode Exit fullscreen mode

Shorthand:

With Template literals we can use backticks (`), which allow us to embed any expression into the string, by wrapping it in ${...} 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
Enter fullscreen mode Exit fullscreen mode

6. For Loop

Longhand:

Using the for loop we can 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
}

//=> ๐Ÿ‰
//=> ๐ŸŠ
//=> ๐Ÿ‡
//=> ๐ŸŽ
Enter fullscreen mode Exit fullscreen mode

Shorthand:

We can achieve the same result using the for...of statement but with very little code like this:

let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', '๐ŸŽ'];

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

//=> ๐Ÿ‰
//=> ๐ŸŠ
//=> ๐Ÿ‡
//=> ๐ŸŽ
Enter fullscreen mode Exit fullscreen mode

7. Arrow Functions

Longhand:

To loop through an array we can also use Array forEach() method. But we have to write a bit more code, which is less than the most common for loop we have seen above, but still a bit more than the for...of statement :

let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', '๐ŸŽ'];

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

//=> ๐Ÿ‰
//=> ๐ŸŠ
//=> ๐Ÿ‡
//=> ๐ŸŽ
Enter fullscreen mode Exit fullscreen mode

Shorthand:

But with Arrow function expressions we can write the full loop code in a single line like this:

let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', '๐ŸŽ'];
fruits.forEach(fruit => console.log( fruit ));  // <-- Magic โœจ

//=> ๐Ÿ‰
//=> ๐ŸŠ
//=> ๐Ÿ‡
//=> ๐ŸŽ
Enter fullscreen mode Exit fullscreen mode

I mostly use forEach loop with arrow functions, but I wanted to show you both the shorthand for looping: for...of statement and forEach loop. So that you can use whichever code you like based on your preference. ๐Ÿ˜ƒ


8. Find an object in an array

Longhand:

To find an object in an array of objects by one of its properties, we usually use for loop like this:

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 }
Enter fullscreen mode Exit fullscreen mode

Shorthand:

Wow! We have to write so much previously, to implement this logic. But with Array find() method and arrow function =>, we can easily achieve 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 }
Enter fullscreen mode Exit fullscreen mode

9. Convert String to Integer

Longhand:

The parseInt() function is used to parse a string and return an integer:

let num = parseInt("10")

console.log( num )         //=> 10
console.log( typeof num )  //=> "number"
Enter fullscreen mode Exit fullscreen mode

Shorthand:

We can achieve the same result by adding a + prefix before the string like this:

let num = +"10";

console.log( num )           //=> 10
console.log( typeof num )    //=> "number"
console.log( +"10" === 10 )  //=> true
Enter fullscreen mode Exit fullscreen mode

10. Short-circuit Evaluation

Longhand:

Mostly if-else statement is used if we have to set a value based on another value is not a falsy value 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"
Enter fullscreen mode Exit fullscreen mode

Shorthand:

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

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

console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"
Enter fullscreen mode Exit fullscreen mode

Basically, expression1 || expression2 is short-circuit evaluated to the truthy expression. So, it's like saying that if the first part is true don't bother evaluating the rest of the expression.


Finally, I would like to end this article by sharing one quote by Jeff Atwood:

Code is only our enemy because there are so many of us programmers writing so damn much of it. If you canโ€™t get away with no code, the next best thing is to start with brevity.

If you love writing code โ€” really, truly love to write code โ€” youโ€™ll love it enough to write as little of it as possible.

If you liked this article, be sure to โค it.

You can also checkout my previous blog:

Happy Coding!


Community Input

Arrow Functions

If you don't need the this context you can shorten even further when you use arrow functions:

let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', '๐ŸŽ'];
fruits.forEach(console.log);
Enter fullscreen mode Exit fullscreen mode

Find an object in an array

You can use object destructure and arrow functions to make it 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 }
Enter fullscreen mode Exit fullscreen mode

Short-circuit Evaluation Alternatives

const getUserRole1 = (role = "USER") => role;
const getUserRole2 = role => role ?? "USER";
const getUserRole3 = role => role ? role : "USER";
Enter fullscreen mode Exit fullscreen mode

Thank you for your feedbacks! โค๏ธ

Top comments (16)

Collapse
 
jessyco profile image
Jessy • Edited

If you don't need the this context you can shorten even further when you use arrow functions.

in your example

let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', '๐ŸŽ'];
fruits.forEach(fruit => console.log( fruit ));
Enter fullscreen mode Exit fullscreen mode

it can be shortened to

let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', '๐ŸŽ'];
fruits.forEach(console.log);
Enter fullscreen mode Exit fullscreen mode

The params of your forEach (item, index) will get passed to the console.log function :)

if you are using custom functions to pass into things like .forEach you can go from this example:

function printMessage(msg) { 
  console.log(msg); 
}
Enter fullscreen mode Exit fullscreen mode

to this

const printMessage = (msg) => console.log(msg);
Enter fullscreen mode Exit fullscreen mode

Hope that helps someone!

Edit: adding example of printMessage

['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', '๐ŸŽ'].forEach(printMessage);
Enter fullscreen mode Exit fullscreen mode

Final note: doing this kind of extraction/abstraction of functionality can help better describe what's happening in your code without needing to add code comments and it can help you unit test your code later on with more context. When you build a larger system, you could have these type of helper functions extracted out of your main code as well. ๐Ÿš€

Collapse
 
palashmon profile image
Palash Mondal

Thanks for sharing! ๐Ÿ˜Š

Collapse
 
crimsonmed profile image
Mรฉdรฉric Burlet

I think this shorthand:

let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', '๐ŸŽ'];

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

//=> ๐Ÿ‰
//=> ๐ŸŠ
//=> ๐Ÿ‡
//=> ๐ŸŽ
Enter fullscreen mode Exit fullscreen mode

If you are logging it can be simplified like this:

let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', '๐ŸŽ'];

// Using forEach method
fruits.map(fruit => console.log(fruit))

//=> ๐Ÿ‰
//=> ๐ŸŠ
//=> ๐Ÿ‡
//=> ๐ŸŽ
Enter fullscreen mode Exit fullscreen mode
Collapse
 
palashmon profile image
Palash Mondal

Thanks for your feedback. โค๏ธ

I have already mentioned that shorthand in the "7. Arrow Functions" section. I hope that is fine.

Happy Coding!

Collapse
 
efpage profile image
Eckehard

Generally for .. of works fine, but was not supported on some older browsers on Android. So, referring to my personal experience, in a real application it can help to use for .. in to get better compatibility.

let fruits = ['๐Ÿ‰', '๐ŸŠ', '๐Ÿ‡', '๐ŸŽ'];

// Using for...of statement 
for (let i in fruits) {
  console.log( fruits[i]);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kanakamvinaykumar profile image
kanakamvinaykumar

Thanks for sharing shorthands

Collapse
 
palashmon profile image
Palash Mondal

Thank you so much. Glad you liked it! ๐Ÿ˜ƒ

Collapse
 
palashmon profile image
Palash Mondal

Thanks for sharing your feedback! ๐Ÿ˜ƒ

Collapse
 
lukegarrigan profile image
Luke Garrigan

Never seen the + prefix one, I look forward to adding this to a PR to confuse everyone. Cheers.

Collapse
 
palashmon profile image
Palash Mondal

Glad you liked it. Have fun adding it to a PR! ๐Ÿ˜„

Collapse
 
heyprotagonist profile image
Anguram Shanmugam

Good one ๐Ÿจ

Collapse
 
palashmon profile image
Palash Mondal

Thank you so much! ๐Ÿ˜ƒ

Collapse
 
palashmon profile image
Palash Mondal

Thanks for sharing!

Collapse
 
cucheng profile image
Trฦฐฦกng ฤรฌnh Chiแบฟn

me too