What is Spread syntax (…) in JavaScript ?

pread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

The Spread Syntax

  • The spread syntax is simply three dots: ...
  • It allows an iterable to expand in places where 0+ arguments are expected.

Definitions are tough without context. Lets explore some different use cases to help understand what this means.

Example #

See the following compare() function compares two numbers:

function compare(a, b) {
    return a - b;
}

In ES5, to pass an array of two numbers to the compare() function, you often use the apply() method as follows:

var result = compare.apply(null, [1, 2]);
console.log(result); // -1

However, by using the spread operator, you can pass an array of two numbers to the compare() function:

let result = compare(...[1, 2]);
console.log(result); // -1

Description

Spread syntax can be used when all elements from an object or array need to be included in a list of some kind.

In the above example, the defined function takes xy, and z as arguments and returns the sum of these values. An array value is also defined.

When we invoke the function, we pass it all the values in the array using the spread syntax and the array name — ...numbers.

If the array contained more than three numbers, e.g. [1, 2, 3, 4], then it would still work fine, except that all four would be passed, but only the first three would be used unless you added more arguments to the function, e.g.:

Thankyou