This post will show you an easy and declarative way to copy or clone the value of an array with Javascript.
To copy an array, we cannot just use =
because it will copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array into a new variable.
By doing so, the new array will not reference the old array address memory.
When building a real-world application, handling state management is super important. So knowing how to create immutable objects (arrays) is super important.
With Array.from
you can create a shallow copy* of an array, so that the original array will be immutable if you do some operations on the copied array.
const movies = ['love','poetry','drama'];
const moviesClone = Array.from(movies);
movies.push('action');
console.log(movies);
// [ 'love', 'poetry', 'drama', 'action' ]
console.log(moviesClone);
// [ 'love', 'poetry', 'drama' ]
Shallow copy means the first level is copied, deeper levels are referenced.
The Array.from
method also (optionally) takes a mapFn
to call on every element on the newly created array. If provided, every value to be added to the array is first passed through this function, and mapFn
's return value is added to the array instead ↓
const movies = ['love','poetry','drama'];
const moviesClone = Array.from(movies, (movie => movie.toUpperCase()));
movies.push('action');
console.log(movies);
// [ 'love', 'poetry', 'drama', 'action' ]
console.log(moviesClone);
//[ 'LOVE', 'POETRY', 'DRAMA' ]
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments section 💬.
My goal with this blog is mainly to create helpful content for
Java
and Javascript
web devs, if you want to discuss a specific topic related to the programming world, you can reach me on my social platforms. Connect with me here LinkedIn • Twitter • Instagram • GitHub or Medium