Nested Array Reference –
An array is a reference type that means it pass a value by reference. If anything happens to the original array or copied array, changed reflected on both the array. But nested array reference is also there.
First, we have a variable array declare using let keyword in which, we assign an array containing a number & nested array.
Then, We assign the first array variable to a new variable newArr which is also declared with the let keyword. But here we use a spread operator to copy an array to a new variable.
Now, we change the index 0 of newArr variable to value 10. Then, we change the first element of nested array to 20.
So, here you need to find out what is the output of array value & array?
Spread Syntax ( … ) –
The spread syntax is used to expand an iterable value like an array, object & string in a place where zero or more arguments are expected. For more detail – Click Here
We use spread operator to removes the referencing of an array but it not able to remove the reference from nested array element.
So, as we know that when we copy array using spread operator which … syntax. The newly assigned variable does not have an array reference of the original array.
But what happens if the array contains an array as an element. Here’s the main question that arises. Because we are using a spread operator to the main array, not to a nested array.
Note: Spread operator/syntax does not remove the reference of the nested array.
I think now you get it, why the answer is 1, 20 because array remains the same as there is no reference passed to the newArr variable.
But nested array still passing their reference to newArr variable. So, if any change occur to nested array element of newArr. Then same changes happen with nested array element of array variable.
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.