DEV Community

Charlotte Fereday
Charlotte Fereday

Posted on

Visualising documentation: JavaScript array.from

Alt Text

Today’s function is array.from(), mdn description here.

This function creates an array from whatever it has been given.

For example, if you give it a string it will split the string into chars and build an array from that. You could also give it an existing array and a function, and it will create a new array from the results of applying the function to each item in the original array.

For this second use case, it's interesting to consider when to use array.from() vs array.map(). Would welcome any comments :)

I've done my own version of the docs with sketches together. Here’s the folder for array.from. Check out the readme to see how you can run the examples.

Top comments (4)

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.