πŸš€ DevOps Certified Professional
πŸ“… Starting: 1st of Every Month 🀝 +91 8409492687 | 🀝 +1 (469) 756-6329 πŸ” Contact@DevOpsSchool.com

What is Spread syntax (…) in JavaScript ?

DevOps

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

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.:

alert( Math.max(3, 5, 1) ); // 5
let arr = [3, 5, 1];
alert( Math.max(arr) );
let arr = [3, 5, 1];
alert( Math.max(...arr) ); // 5 (spread turns array into a list of arguments)
// --------------------------------------------
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
console.log(sum.apply(null, numbers));
// expected output: 6
// --------------------------------------------

Thankyou