JavaScrip Spread syntax –
...) is used to expand the iterable values like an array, object, or string where one or more argument is expected.
It’s mostly used with array and object for copying one array into another array without passing a reference.
It’s syntax looks like –
So first, we declare a variable arrOne using let keyword and assign an array to it.
let arrOne = [1, 2, 3];
Now, we declare an another variable arrTwo using let and assign an array to it.
let arrTwo = [4, 5, 6];
In the next step, we are using array push method with arrOne and inside it we are passing arrTwo with spread syntax.
Their is a trick part also as we are now changing the first element of the arrTwo to 7
arrTwo = 7;
Finally, let me in the comment section what is the output of arrOne 3rd index now.
You got the answer now which is 4. But how it can be 4.
Let me explain to you –
So, first we are pushing arrTwo variable to arrOne using spread syntax. Like this,
But as we know, spread syntax expand the values of array and array push method can push multiple element if they are comma separated. So it looks like –
arrOne.push(4, 5, 6);
Now, it push all values to arrOne. In the next step, we change the value of arrTwo of 0 index to 7.
But as there is no reference is passed to arrOne so no change happens in arrOne values. So, your final arrOne looks like –
[1, 2, 3, 4, 5, 6]
That’s why we get an answer 4
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – What value should return when adding multiple arrays
- JS Quiz – What happens when add or sub null value
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.