Understanding JavaScript Variable Mutability and Immutability | ES6 Course

JavaScript Variable Mutability and Immutability: JavaScript is one of the most popular programming languages today, and its flexibility allows developers to create complex and dynamic applications. One crucial aspect of JavaScript is understanding the concept of variable mutability and immutability. In this article, we will delve into the definitions of mutable and immutable data types and explore their usage in JavaScript. We will also discuss the advantages of using immutable variables and how to make JavaScript variables immutable.

What are Mutable and Immutable Data Types in JavaScript?

In JavaScript, data types can be divided into two categories: mutable and immutable. Mutable data types can be changed after creation, while immutable data types cannot.

Mutable data types include objects, arrays, and functions, while primitive data types, such as strings, numbers, and booleans, are immutable.

Examples of Mutable and Immutable Data Types in JavaScript

Here are some examples of mutable and immutable data types in JavaScript:

Mutable Data Types:

Objects:

let person = { name: "John", age: 30 }; 
person.age = 31; // This is a mutable operation

Arrays:

let colors = ["red", "green", "blue"]; 
colors.push("yellow"); // This is a mutable operation

Functions:

function add(x, y) { return x + y; } 
add = function(x, y) { return x - y; }; // This is a mutable operation

Immutable Data Types:

Strings:

let greeting = "Hello"; 
greeting.toUpperCase(); // This is an immutable operation

Numbers:

let x = 10; 
x = 20; // This is a mutable operation

Booleans:

let isTrue = true; 
isTrue = false; // This is a mutable operation

JavaScript Variable Mutability and Immutability in Detail

Mutable Variables in JavaScript

As previously mentioned, mutable variables can be modified after creation. This means that if you change the value of a mutable variable, it will affect all references to that variable. For example:

let person = { name: "John", age: 30 }; 
let newPerson = person;
person.age = 31;
console.log(person.age); // Output: 31 
console.log(newPerson.age); // Output: 31

In this example, we created an object called “person” and assigned it to a variable. We then assigned the same object to another variable called “newPerson.” When we changed the value of the “age” property in the “person” object, it also changed in the “newPerson” object.

Immutable Variables in JavaScript

In contrast, immutable variables cannot be changed after creation. If you change the value of an immutable variable, it will create a new value instead of modifying the original. For example:

let greeting = "Hello"; 
let newGreeting = greeting.toUpperCase();
console.log(greeting); // Output: "Hello" 
console.log(newGreeting); // Output: "HELLO"

In this example, we created a string variable called “greeting” and assigned it the value “Hello.” We then created another variable called “newGreeting” and used the “toUpperCase()” method to create a new value. The original “greeting” variable was not modified, and a new value was created instead.

Mutable vs. Immutable Variables

Now that we know what mutable and immutable values are, let’s take a look at mutable and immutable variables.

In JavaScript, variables are used to store values. A mutable variable is a variable that can be changed to point to a different value, while an immutable variable is a variable that cannot be changed to point to a different value.

Let’s look at some examples:

// Mutable variable let myObj = { name: "John", age: 30 }; 
myObj.age = 31; // valid - changing the value of a mutable object property
// Immutable variable const myNum = 10; 
myNum = 11; // invalid - cannot change the value of an immutable variable

As we can see from the above examples, we can change the value of a property of a mutable object, but we cannot change the value of an immutable variable.

Pros and Cons of Mutable and Immutable Variables

Both mutable and immutable variables have their advantages and disadvantages, and the choice between them depends on the specific use case.

Pros of Mutable Variables

  • Mutable variables can be more efficient when dealing with large amounts of data because you don’t need to create a new object every time you want to make a change.
  • Mutable variables can be more convenient when you want to make many changes to the same object.

Cons of Mutable Variables

  • Mutable variables can be error-prone because they can be changed accidentally or by multiple parts of the code at the same time.
  • Mutable variables can make it harder to reason about the code because their value can change at any time.

Pros of Immutable Variables

  • Immutable variables can make the code more predictable because their value cannot be changed after they are created.
  • Immutable variables can make the code easier to reason about because their value cannot be changed.

Cons of Immutable Variables

  • Immutable variables can be less efficient when dealing with large amounts of data because you need to create a new object every time you want to make a change.
  • Immutable variables can be less convenient when you want to make many changes to the same object.

How to Create Immutable Variables in JavaScript

Creating immutable variables in JavaScript involves using data types that are inherently immutable or making use of techniques that prevent the mutation of mutable data types. Here are some techniques that can be used to create immutable variables:

Using const keyword

The const keyword can be used to create immutable variables in JavaScript. Once a value has been assigned to a variable using const, it cannot be reassigned or changed. For instance:

const x = 10;
x = 20; // error: Assignment to constant variable

Using Object.freeze()

The Object.freeze() method can be used to create immutable objects in JavaScript. This method freezes an object by preventing the addition, deletion, or modification of its properties. For instance:

const obj = { name: 'John', age: 30 };
Object.freeze(obj);
obj.age = 40; // error: Cannot assign to read only property 'age' of object

Using the Spread Operator

The spread operator (...) can be used to create copies of mutable data types, such as arrays and objects. By creating a new copy, we can prevent the original data from being mutated. For instance:

const arr1 = [1, 2, 3];
const arr2 = [...arr1]; // creates a copy of arr1
arr2.push(4); // modifies the copy, not the original
console.log(arr1); // [1, 2, 3]
console.log(arr2); // [1, 2, 3, 4]

Benefits of Immutability in JavaScript

Immutability can offer several benefits when working with JavaScript variables. Some of these benefits include:

  • Predictability: When a variable is immutable, its value cannot be changed unexpectedly. This can help make our code more predictable and easier to reason about.
  • Performance: Since immutable data does not change, it can be cached and reused more easily. This can help improve performance, especially in cases where large amounts of data need to be processed.
  • Concurrency: In multi-threaded environments, immutable data can be shared safely between threads without the need for locks or other synchronization mechanisms.
  • Debugging: When a variable is immutable, it is easier to track changes to its value. This can help with debugging and understanding the flow of data in our code.

Conclusion

In conclusion, variables are an essential part of JavaScript programming, and understanding their mutability and immutability is crucial for writing robust and efficient code. By creating immutable variables and taking advantage of their benefits, we can make our code more predictable, performant, and easier to maintain.

Resources for Learning More

There are many resources available for learning JavaScript, from online courses to books and tutorials. Some popular resources include CodecademyW3Schools, and the Mozilla Developer Network.

Also Read:

Leave a Comment