Arrays and References

Add and remove items, then see that assigning an array copies the reference, not the array. Spread makes a real copy.

JavaScript · beginner · 6 min · 9 steps · free

What you'll learn

Arrays.js

const fruits = ['apple', 'banana'];
fruits.push('cherry');
const first = fruits[0];
const last = fruits.pop();
const sameList = fruits;
sameList.push('mango');
const copy = [...fruits];
copy.push('kiwi');
console.log(fruits, copy);

Step by step

  1. fruits is created and points to a new Array: ["apple", "banana"].
  2. push adds to the end of the same array. fruits is a const, but const only stops reassigning the variable, not changing the array.
  3. first is created with the value "apple".
  4. pop removes the last item and returns it.
  5. sameList = fruits copies the arrow, not the array: both names point to one array.
  6. Pushing through sameList changes the one shared array.
  7. [...fruits] spreads the items into a brand-new array: a real copy.
  8. Only the copy gets "kiwi".
  9. It prints [ 'apple', 'banana', 'mango' ] [ 'apple', 'banana', 'mango', 'kiwi' ].

Common mistakes

Best practices

Key takeaways

Check yourself

const a = [1]; a.push(2); allowed?

Answer: Yes. The array changes, not the variable.

b = a; b.push(3); a has 3?

Answer: Yes

·

More in Objects and Arrays