Spread Operator and It’s uses in javascript

Share

I was working on a personal project in javascript and I came across a spread operator so I thought it’ll be a good idea to have some good insights about it.

The spread operator (…) helps you expand iterable into individual elements.

The spread syntax works within array literals, function calls, and initialized property objects to spread the values of iterable objects into separate items in javascript . So effectively, it does the opposite thing from the rest operator.

We’ll talk about the rest operator in the next one.

Spread syntax looks exactly like rest syntax. In a way, spread syntax is the opposite of rest syntax. Spread syntax expands an array into its elements, while rest syntax collects multiple elements and condenses them into a single element.

Example 1:Use of Spread Operator to convert string intro individual array elements.

const myname = "suraj gaire"

console.log([...myname])

//output:- ['s','u','r','a','j',' ','g','a','i','r','e']

Let’s see how the spread operator works on an array literal.

const myname = ["suraj gaire"];

const aboutMe = [...myname, "is", "my", "name"];

console.log(aboutMe);

//output:- ['suraj gaire','is','my','name']

We can see in two examples how the spread operator works on string and array literal.

Now let’s see spread operator works in a function call.

const numbers = [1, 2, 3, 4];

function addNumber(a, b, c, d) {
  return a + b + c + d;
}

console.log(addNumber(...numbers));

// output:- 10

Here we have spread the array content i.e. we have spread the numbers as individual elements as 1,2,3,4 and pass them into the addNumber function.

Spread syntax can be used when all elements from an object or array need to be included in a new array or object.

Only iterable objects, like array can be spread in array and function parameters. Many objects are not iterable, including all plain objects that lack a Symbol.iterator method:

const obj = { key: "value" };

console.log(...obj);

It throws an error saying the object is not iterable:

output of above code

We can spread an array into objects using the spread operator:

const numbers = [1, 2, 3, 4];
console.log({ ...numbers });

//Output is: { '0': 1, '1': 2, '2': 3, '3': 4 }

This was some insight about the spread operator. You can learn more from here.

Learn more about other javascript topics from here.

Share