Skip to content
Ayotl

← Data structures from scratch · Lesson 2/32

Values and references

✕
1/8

Simple values get copied

Numbers, strings and booleans (true/false) are primitive values. When you write b = a, b gets a copy: changing b afterwards doesn't touch a.

leccion.js

$ node leccion.js

Press RUN (or Ctrl+Enter).

What to look at

a is still 5 and saludo is still "hola": each variable has its own value.

The whole lesson on one page

Simple values get copied

Numbers, strings and booleans (true/false) are primitive values. When you write b = a, b gets a copy: changing b afterwards doesn't touch a.

let a = 5;
let b = a;
b = 8;
console.log(a, b);

let saludo = "hola";
let otro = saludo;
otro = otro + " Sahuayo";
console.log(saludo, "|", otro);

a is still 5 and saludo is still "hola": each variable has its own value.

Objects get shared

With arrays and objects something else happens. The variable doesn't hold the array: it holds where it is (a reference, like a house's address). b = a copies the address, not the house. Both point to the same array, so whatever you do through b shows up through a.

This is the most important idea of the unit: linked lists, trees and graphs are made of objects that point to each other through references.

const a = [1, 2, 3];
const b = a;        // the same address
b.push(4);
console.log(a);

const ficha = { nombre: "Rosa", puntos: 10 };
const misma = ficha;
misma.puntos = 99;
console.log(ficha.puntos);

a has the 4 too, and the original card ended up with 99 points. There were never two arrays or two cards: there were two names for the same thing.

Real copies, and comparing

If you want another array, you have to create it. [...a] makes a new one with the same items (a shallow copy: objects inside are still shared). structuredClone(a) copies everything, all the way down.

And watch out for ===: with objects it compares addresses, not contents. Two arrays that look the same inside are not "the same" array.

const a = [1, 2];
const b = [...a];
b.push(3);
console.log(a, b);

console.log([1, 2] === [1, 2]);
console.log(a === a);

const grupos = [["Ana"], ["Beto"]];
const superficial = [...grupos];
superficial[0].push("Caro");
console.log(grupos[0]);
  • a stayed [1, 2]: now there really are two arrays.
  • [1, 2] === [1, 2] is false: two different addresses.
  • The last case is the shallow-copy trap: the outer array is new, but ["Ana"] was shared and gained "Caro".