Skip to main content

Copying an array variable to another variable

Published 1 min readMarkdown

A common mistake newbies in JavaScript make, is referencing arrays instead of copying it when using the assignment operator.

let pokemons = ['pikachu', 'eevee', 'snorlax', 'charmander', 'charizad'];

// This will point (create a reference) new_pokemons to pokemons
let new_pokemons = pokemons;

new_pokemons.push('mewtwo');

console.log("new_pokemons = ", new_pokemons);
console.log("pokemons = ", pokemons);

Output:

new_pokemons = [ 'pikachu', 'eevee', 'snorlax', 'charmander', 'charizad', 'mewtwo' ] pokemons = [ 'pikachu', 'eevee', 'snorlax', 'charmander', 'charizad', 'mewtwo' ]

let pokemons = ['pikachu', 'eevee', 'snorlax', 'charmander', 'charizad'];

// This will create a copy of the pokemon array and save it as a new array
let new_pokemons = [...pokemons];

new_pokemons.push('mewtwo');

console.log("new_pokemons = ", new_pokemons);
console.log("pokemons = ", pokemons);

Output:

new_pokemons = [ 'pikachu', 'eevee', 'snorlax', 'charmander', 'charizad', 'mewtwo' ] pokemons = [ 'pikachu', 'eevee', 'snorlax', 'charmander', 'charizad' ]

In the second one, mewtwo is included only in new_pokemons.

About the author

  • I am a web consultant from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in

No comments yet. Be the first to comment.