Mutability and Immutability of Variables and their values in JS
Photo credits to https://snipcart.com/blog/why-javascript-benefits

Mutability and Immutability of Variables and their values in JS

Prerequisites: A few programming basics (Variables, data types, and arrays)

IMPORTANT NOTE: When taking a JS course and the instructor starts talking about variables, don't feel that this is nothing but easy stuff you already know!

Every programming language has its own philosophy. While there are many common areas between all programming languages, we cannot deny that each one has its nature, low-level details, etc. In this article, we will talk about some interesting things about variables and their values in JS. I hope you all will find it useful.

Boxes that hold some data?

A common analogy that some people use to describe a variable is to say that it is like a box containing things inside it. Forget this analogy. It won't be that accurate in the JS context.

So, what variables are?

Variables in JS are somewhat like pointers that point to specific values in memory.

let number = 20;        
Whiteboarding demonstrates the idea

As it appears on the whiteboard, the number is nothing but something that points to the value 20.

Immutability and mutability

Here I want to categorize each of them into two categories:



Immutable and mutable variables

It only affects how it can point to other things in the future. Look at this example, where the variable age is mutable (which means that we can change what it points to):

let age = 10;
age = 18;
console.log(age); // will output 18        

In the first line of code, we created a variable called age and made it point to the value 10.

Then in the second line of code we actually moved this arrow towards a different value which is 18:

This variable "age" is mutable as it can be assigned to new values without restrictions! Let's look at another different case:

const a = 10;
a = 18;        

To know what would be the result, let's try it in the console:

This error means that you can't assign this variable a to another value, which means it is immutable!

How to create variables mutable/immutable

You might have noticed that when we used the keyword let before the variable name, the variable was mutable, but when using const, it was immutable. I will discuss let, var, and const in another separate article. For now, know that any variable declared with const will be immutable, while any variable declared with let will be mutable (meaning you can assign it to new values without any errors raised!).

Immutable and mutable values

Not only variables, but values themselves can also be mutable or immutable. This distinction is crucial when dealing with complex data structures.

Mutable Values:

  • Objects and arrays in JavaScript are mutable. This means that you can change the contents of an object or array without changing the reference.

  • Example:

let person = { name: "Alice", age: 25 };
person.age = 26; // Mutates the person object
console.log(person.age); // Outputs: 26        

Immutable Values:

  • Primitive values like strings, numbers, booleans, null, and undefined are immutable. This means that you cannot change the value once it is created.
  • Example:

let name = "Alice";
let newName = name.toUpperCase(); // Creates a new string
console.log(name); // Outputs: "Alice"
console.log(newName); // Outputs: "ALICE"        

Mixing: Mutable Value with Immutable Variable (Array Example)

An interesting case arises when you have a mutable value assigned to an immutable variable. For instance, consider an array assigned to a const variable. The array itself is mutable, meaning you can change its contents, but the reference to the array is immutable, meaning you cannot reassign the variable to a different array.

Example:

const arr = [1, 2, 3];

// You can modify the contents of the array
arr.push(4);
console.log(arr); // Outputs: [1, 2, 3, 4]

// You cannot reassign the array
arr = [5, 6, 7]; // TypeError: Assignment to constant variable.        

In this example:

  • const arr = [1, 2, 3]; declares an array arr as a constant variable.
  • The contents of the array can be modified, as seen with arr.push(4);.
  • However, attempting to reassign arr to a different array results in a TypeError.

This demonstrates that while const makes the variable immutable (you cannot reassign it), the value it holds (in this case, the array) can still be mutable and its contents can be modified.


Conclusion

In JavaScript, let allows variable reassignment, making them mutable, while const creates immutable bindings for variables but doesn't prevent changes to mutable values like arrays and objects held within. These distinctions help maintain code predictability and manage data effectively in JavaScript applications.


Abdulrahman hashem

Front-End developer

8 个月

keep going ????

回复

要查看或添加评论,请登录

Aya Ragab的更多文章

  • ALX SE — How I Survived In This Journey of Ups and Downs

    ALX SE — How I Survived In This Journey of Ups and Downs

    Introduction: My Start with ALX SE I was a fresh student in my faculty—Computer science faculty—when I joined the ALX…

    19 条评论
  • JavaScript weird things | Part 2

    JavaScript weird things | Part 2

    Prerequisite: foundational knowledge in programming. NOTE: This article will give a brief introduction to various…

    1 条评论
  • JavaScript weird things | Part 1

    JavaScript weird things | Part 1

    Prerequisite: foundational knowledge in programming. NOTE: This article will give a brief introduction to various…

    2 条评论
  • JavaScript landscape | beginner guide

    JavaScript landscape | beginner guide

    Prerequisites for this article: none. Have you ever felt overwhelmed by the JavaScript jargon? Or asked yourself, "What…

    2 条评论
  • Objects nature in JavaScript (1) | for beginners

    Objects nature in JavaScript (1) | for beginners

    This is the first article I wrote in my newsletter "Intro to JavaScript" and I want to point out that having a strong…

    1 条评论

社区洞察

其他会员也浏览了