JS Startup

Challenges, Tips & Tricks & Tutorials

JavaScript Quiz – Did really the reference pass using Array.from() method

JavaScript Quiz – Did really the reference pass using Array.from() method

Array.from() method –

The javascript array.from() method ( Array.from() ) is used to create a new from a given array. We don’t just need to pass the array, even if you pass the string also it gets converted to an array. Like this.

Array.from(“JS Startup”) = [ ‘J’, ‘S’, ”, ‘S’, ‘t’, ‘a’, ‘r’, ‘t’, ‘u’, ‘p’ ];

And it’s syntax looks like –

Array.from(object, mapFunction, thisValue)

To know more about the javascript Array.from() method click here.

JavaScript Question

Now, in this javascript quiz code you need to figure out that the array return from the Array.from() method still passing the reference to new javascript array.

First we declare a variable array using let keyword and assign an array with number elements inside of it.

let array = [1, 2, 3, 4, 5];

Now, we change the first index of array to 0. Like

array[0] = 0;

In the next, we create an another variable newAraay using let and assign Array.from(array) to it.

let newArray = Array.from(array);

Fun part begin, so we change the first index of newArray to 10 as Array.from() method return an array.

newArray[0] = 10;

Now, what should be the value of array[0] which we are console log now any guess.

Answer – 0

Click To Run Code

Explanation

Now, you know the answer is 0 but why it give you 0 instead of 1 or 10.

Let me explain you about it clearly.

So, when we change the first index which is 0 index of array to value 0. Then it obviously change it 0.

Then, we assign array to newArray variable using Array.from() method by passing the array variable to it.

Then we change the 0 index of newArray to 10. But as Array.from() gives a new array mean it’s just a shallow copy. So there is no change happen to main array.

That’s why we get an answer “0“.

I hope you understand the concept and logic behind it.

But wait, i have something more for you –

Check out our other javascript quiz – 

  1. JS Quiz – What happens when add or sub null value
  2. JavaScript Quiz – what really spread syntax with array pushing
  3. JavaScript Quiz – what is really object entries method return
  4. JS Quiz – Did really string substring method can do this

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
13 Shares
Share via
Copy link