Array from method –
Array.from()) is used to create a new array from an array-like or iterable object.
Array from method create a shallow copied array.
It’s syntax look like –
Array.from(object, mapFunction, thisValue)
let array = [1, 3, 5];
In the next step, we use an Array.from() and pass an array variable to it and also pass a function which multiplies each element with 3 like an array map method.
And assign the array returned from Array.from() to new variable newArray which is created with let.
let newArray = Array.from(array, x => x*3);
Now, we change index 1 of the array variable to 6. And then check the value of index 1 of the newArray variable.
array = 6;
So, Any guess what will the output of console log ?
Now, you know the answer is 9. But you want to know why, it should be 6 or does it work like a map in array from method. Let me explain.
So, it’s true that Array.from() can be work like an Array.map() as it also contains a map function in it that runs for every element in the array.
As if you remember that Array.from() creates a new array and it’s a shallow copy. This means any change in the array variable will not reflect on the newArray.
Array.from() with mapFunction –
And we use a mapFunction in array from method to change the element value by multiply 3. So it should be like.
let newArray = [3, 9, 15];
At last, That’s why we get an answer “9“.
Let me know in the comment section, what you think about it.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – can it uppercase the string first letter
- JS Quiz – can string split method will be limited
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.