Essential JavaScript

Const Objects

We have used the const keyword to declare variables that can't be reassigned.

When we declare a primitive variable, like a string or number, this means the variable can't be changed at all.

However, look at what happens if we declare an object variable using const:

const person = {
  firstName: 'Linn',
  lastName: 'Yotam',
  age: 39,
};
console.log(person.age); // 39
person.age++;
console.log(person.age); // 40

The Constant Object

Notice how the age property was able to change?

In the example above, the const keyword prevents us from changing what the variable person points to.

However, it doesn't prevent us from updating the object that the variable points to.

We would still run into an error if we tried re-assigning the variable itself:

const person = {
  firstName: 'Linn',
  lastName: 'Yotam',
  age: 39,
};
person = {
  firstName: 'New',
  lastName: 'Person',
  age: 1,
};

The above code will give us an error.

"Passed by Value"

In JavaScript, when we declare a variable, that variable points to a piece of data.

For primitive data types like strings and numbers, that data is "passed by value". In other words, no two variables can actually contain the same primitive value. Take a look:

let first = 'John';
let second = first;

console.log(first); // "John"
console.log(second); // "John"

second = "James";

console.log(first); // "John"
console.log(second); // "James"

See how the variables don't point to the same data behind the scenes? If they did, then updating second would have updated first as well.

Instead, the current value of first was assigned to second. Each variable had its own copy of the data to work with.

"Passed by Reference"

Unlike primitives, objects are passed by reference. That means that each variable actually refers to the same object:

const first = { name: 'John' };
const second = first;

console.log(first); // { "name": "John" }
console.log(second); // { "name": "John" }

first.name = 'James';

console.log(first); // { "name": "James" }
console.log(second); // { "name": "James" }

Since both variables point to the same object, updating a property of that object through either variable name will change the one object that is behind both variables.


Learning Goals

Code Editor