Anjanesh

Anjanesh

Copying an array variable to another variable

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.

 
Share this