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)
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;
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 = 10;
Now, what should be the value of array which we are console log now any guess.
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 –
- JS Quiz – What happens when add or sub null value
- JS Quiz – Did really string substring method can do this
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.