...

/

Value vs. Reference

Value vs. Reference

Learn how some data types are copied by value and others by reference, and what this means when we write code. This concept is at the root of countless bugs that plague websites today. A simple look at computer memory explains what’s happening.

Preface

I’d like to begin this lesson by saying that this lesson is meant to provide a useful model for understanding the behavior of variables in JavaScript. It is not necessarily how engines implement the behavior of variables, as each engine may do it differently, but it provides a model that fits the behavior correctly and helps explain what we observe.

As you advance in your software career, you’ll gain a deeper understanding of how values are treated. For now, this lesson will provide a suitable model for understanding the behavior we observe when working with variables in JavaScript.

Values & References

JavaScript has 5 data types that are copied by value: Boolean, null, undefined, String, and Number. We’ll call these primitive types.

JavaScript has 3 data types that are copied by having their reference copied: Array, Function, and Object. These are all technically Objects, so we’ll refer to them collectively as Objects.

Primitives

If a primitive type is assigned to a variable, we can think of that variable as containing the primitive value.

const x = 10;
const y = 'abc';
const z = null;

x contains 10. y contains 'abc'. To cement this idea, we’ll maintain an image of what these variables and their respective values look like in memory.

Variables Values
x 10
y 'abc'
z null

When we assign these variables to other variables using =, we copy the value to the new variable. They are copied by value.

Press + to interact
Node.js
const x = 10;
const y = 'abc';
const a = x;
const b = y;
console.log(x, y, a, b);
// -> 10, 'abc', 10, 'abc'

Both a and x now contain 10. Both b and y now contain 'abc'. They’re separate, as the values themselves were copied.

Variables Values
x 10
y 'abc'
a 10
b 'abc'

Changing one does not change the other. Think of the variables as having no relationship to each other.

Press + to interact
Javascript (babel-node)
const x = 10;
const y = 'abc';
let a = x;
let b = y;
a = 5;
b = 'def';
console.log(x, y, a, b); // -> 10, 'abc', 5, 'def'

Objects

This will feel confusing, but bear with me and read through it. Once you get through it, it’ll seem easy.

Variables that are assigned a non-primitive value are given a reference to that value. That reference points to the object’s location in memory. The variables don’t actually contain the value.

Objects are created ...