What is … ?

The ‘…’ or spread operator is a useful tool for syntax in JavaScript. It can be used in:

  • Function calls
  • Arrays/Strings
  • Rest Parameters

Let’s go through how to use it in each of the mentioned uses.

Function Calls

1. ‘new’ object using array

Traditionally, you cannot use the ‘new’ keyword to create an object using an array directly. I’m talking about something like a new Date(array) (a new Date Object). Using an array in the constructor is not valid but with ‘…’ , it becomes possible:

const date = [2020, 0, 1];  // 1 Jan 2020
const dateObj = new Date(...date);

console.log(dateObj);
// VM60:1 Wed Jan 01 2020 00:00:00 GMT-0500 (Eastern Standard Time)

2. ‘apply()’ method

The ‘…’ can be used just like the apply() method in JavaScript.

For example, instead of using apply():

const array = ['a', 'b'];
const elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

You can use ‘…’ for a more concise syntax like so:

const array = ['a', 'b'];
const elements = [0, 1, 2];
array.push(...elements);
console.info(array); // ["a", "b", 0, 1, 2]

For more details on how _apply()_ works, you can read up at w3schools.com/js/js_function_apply.asp.

#beginners-guide #javascript #web-development #programming

A Beginner’s Guide to … in JavaScript
1.35 GEEK