Practice: Immutable vs. Mutable in JavaScript

Site: Saylor Academy
Course: PRDV401: Introduction to JavaScript I
Book: Practice: Immutable vs. Mutable in JavaScript
Printed by: Guest user
Date: Sunday, May 19, 2024, 3:42 AM

Description

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!

Table of contents

Primitive

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. There are 7 primitive data types: string, number, bigint, boolean, undefined, symbol, and null.

Most of the time, a primitive value is represented directly at the lowest level of the language implementation.

All primitives are immutable, i.e., they cannot be altered. It is important not to confuse a primitive itself with a variable assigned a primitive value. The variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered.


Source: Mozilla, https://developer.mozilla.org/en-US/docs/Glossary/Primitive
Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.

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.