DEV Community

Discussion on: Visualising documentation: JavaScript array.from

Collapse
 
stevescruz profile image
Steve Cruz • Edited

For those reading this post I'll show you another interesting use for array.from.

Try this:

const pets = ["dog", "cat", "hamster"];
const animals = pets;

animals.push("snake");

console.log(pets);
console.log(animals);

Then try this:

const pets = ["dog", "cat", "hamster"];
const animals = Array.from(pets);

animals.push("snake");

console.log(pets);
console.log(animals);

Array.from can be used to create a deep copy of an array. If we simple assign a value of an existing array to a new array it creates a shallow copy of the existing array.

Collapse
 
charlottebrf_99 profile image
Charlotte Fereday

Thanks for this :). The two snippets you’ve given seem exactly the same to me - am I missing something?

Collapse
 
stevescruz profile image
Steve Cruz • Edited

Yes, you are right Charlotte, I corrected my mistake.

I just edited the second snippet, in the second line I was supposed to use Array.from .

I hope it makes sense now.

Thread Thread
 
charlottebrf_99 profile image
Charlotte Fereday

I see! Very cool, thanks for sharing hadn't thought of that use case.