DEV Community

Moisés Fernández Zárate
Moisés Fernández Zárate

Posted on

JavaScript | Mutability vs Immutability

In JavaScript whether a variable is mutable or immutable it depends on its type and there are only two types of variables in which data is stored: primitive and reference.

Primitive Type (Immutability)

All the JavaScript primitive types that are the atomic values stored to a variable, which are the following:

  • Number
  • Boolean
  • String
  • Null
  • Undefined
  • Symbol

Following is an example of how these primitive types are stored in JavaScript:

let dog = "Chopper";
let dog2 = dog;

dog = "Cody";
console.log(dog2); // Expected output: Chopper
Enter fullscreen mode Exit fullscreen mode

The variable 'dog2' is created as a new space in memory and is allocated with the same value as the variable 'dog', it is not a reference. Modifying the first variable won't change the value stored in the second variable because it is not a reference. This is a perfect example of Immutability in JavaScript.

Reference Type (Mutability)

This type is more complicated than simple and atomic values, they consist of multiple properties and are stored as references in memory. In JavaScript exist the following reference types:

  • Array
  • Object
  • Function

Following is an example of how these reference types are stored in JavaScript:

let dog = {name: 'Chopper', age: '5'};
let dog2 = dog;

dog.name = "Cody";
console.log(dog2); // Expected output: {name: "Cody", age: "5"}
Enter fullscreen mode Exit fullscreen mode

The variable 'dog2' is created as a new variable, but only as a reference to the first object. Modifying the first variable affects the value shown when printing the second variable because it is a reference to the first object. This is a perfect example of Mutability in JavaScript.

Top comments (0)