Practice: Immutable vs. Mutable in JavaScript

Understanding the concept of mutable and immutable in JavaScript is vital to prevent programming errors. For example, we know that numbers are immutable. This article presents examples that you can try to understand this concept. This exercise does not count towards your grade. It is just for practice!

Primitive

Example

This example will help you understand that primitive values are immutable. Start by opening a Developer Console in your browser. The sequence is ctrl+shift+J on Windows and cmd+option+J on the Mac. Then, you'll use the "console.log" method to write output to the developer console.


JavaScript

// Using a string method doesn't mutate the string
var bar = "baz";
console.log(bar);               // baz
bar.toUpperCase();
console.log(bar);               // baz

// Using an array method mutates the array
var foo = [];
console.log(foo);               // []
foo.push("plugh");
console.log(foo);               // ["plugh"]

// Assignment gives the primitive a new (not a mutated) value
bar = bar.toUpperCase();       // BAZ

A primitive can be replaced, but it can't be directly altered.