JS Startup

Challenges, Tips & Tricks & Tutorials

JavaScript Quiz – Does nested array reference removed by spread syntax

JavaScript Quiz – Does nested array reference removed by spread syntax

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.

Question –

The main idea behind this quiz to find that nested array reference passed to a new variable when copy using the spread syntax.

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[0] value & array[1][0]?

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.

Answer – 1, 20

Click To Run code

Explanation –

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[0] 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.

Check out our previous challenge – FIND OUT THE SIZE OF A JAVASCRIPT MAP OBJECT

Conclusion

To participate in our javascript quiz or challenges, tutorial, tips & tricks make sure to join our jsstartup newsletter. So, you can able to participate in our daily challenges & learn the javascript concept.

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.

Leave a Reply

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

Back to top
0 Shares
Share via
Copy link