Javascript spread syntax

Spread syntax is simply denoted as three ... dots.it allows an array expression or string or anything which can be iterating to be expanded in places where zero or more arguments for function calls or elements for array are expected.




Example: Without Spread syntax.

const arr = [1, 3];
function add(x, y) // here receive parameter x, y
  {
     return x + y; // return addition of x and y
  }
const result = add(arr[0], arr[1]); // here pass manually array's values
console.log(result); // Output 4

Example: Using Spread syntax.

const arr = [1, 3];
function add(x, y) // here receive parameter x, y
  {
     return x + y; // return addition of x and y
  }
const result = add(...arr); // i.e spread syntax automatically assign the values
console.log(result); // Output 4

Let us understand the spread syntax in other way.

Example #1: Inserting arrays.

 var first_arr = ['c', 'd'];
 var new_arr   = ['a', 'b', first_arr, 'e', 'f'];

In above code, we’ve created an array first_arr and another array new_arr which contains our first_arr array. when we print the new_arr using console.log, the output will come:

  console.log(new_arr); // Output ['a', 'b', ['c', 'd'], 'e', 'f']

are you expecting that result?

we write the same code using spread syntax. lets see what will happen.

 var first_arr = ['c', 'd'];
 var new_arr   = ['a', 'b', ...first_arr, 'e', 'f']; // use spread syntax

In above, we’re using the spread syntax to insert the first_arr array into the new_arr array. lets see what will be the output come ?

  console.log(new_arr); // Output ['a', 'b', 'c', 'd', 'e', 'f']

Nice !

Example #2: Copy an Array.

 var new_arr  = ['a', 'b', 'c', 'd'];
 var new_arr2 = new_arr;
 new_arr2.push('e');

In above code, we’ve created a new array new_arr with some values and copy new_arr to new_arr2.it means new_arr’s reference (address) has been assigned to new_arr. it means if we do anything with new_arr2, it will also effect the new_arr and vice-versa because they shared the same reference (address).

We’ve pushed a new element ‘e’ into new_arr2.we’ll see that the e value was also added to new_arr

let’s see what will be the output come.

 console.log(new_arr);  // Output ["a", "b", "c", "d", "e"]
 console.log(new_arr2); // Output ["a", "b", "c", "d", "e"]

we saw that ‘e’ also added to new_arr because shared the same reference.

No need to worry! here we can use spread operator to remove this kind of ambiguity.

 var new_arr  = ['a', 'b', 'c', 'd'];
 var new_arr2 = [...new_arr];
 new_arr2.push('e');
 console.log(new_arr);  // Output 'a', 'b', 'c', 'd'
 console.log(new_arr2); // Output 'a', 'b', 'c', 'd', 'e'

That’s it!. Please share your thoughts or suggestions in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *