Wednesday, February 19, 2025

JavaScript, Primitive types are immutables?



Are other primitive types in JavaScript are immutable?


Yes, in JavaScript, most primitive types are immutable, meaning that once a value of a primitive type is created, it cannot be altered. However, it's important to understand that immutability refers to the value itself, not the variable that holds the value. Here's a breakdown of the primitive types and their immutability:

Immutable Primitive Types:
String:

Immutable: Once a string is created, its value cannot be changed. Any operation on a string that seems to modify it (e.g., slicing, concatenation) will return a new string, not modify the original one.


let str = "Hello";
str[0] = "J";  // Does nothing
console.log(str);  // "Hello" (unchanged)
Number:

Immutable: Numbers in JavaScript are immutable. When you perform arithmetic operations, a new number is created, and the original number remains unchanged.


let num = 42;
num = num + 10;  // Creates a new number
console.log(num);  // 52
Boolean:

Immutable: Boolean values (true and false) are immutable. Changing them requires reassigning them to a different value.


let isTrue = true;
isTrue = false;  // Assigning a new value, the original is unchanged
console.log(isTrue);  // false
Undefined:

Immutable: The value undefined is a single, fixed primitive and cannot be changed. If a variable is undefined, it simply means it has not been assigned a value.


let a;
console.log(a);  // undefined
a = 5;
console.log(a);  // 5
Null:

Immutable: The value null is also immutable. It's a special value that represents the absence of any object or value.


let obj = null;
obj = {};  // obj now refers to a new object
Symbol:

Immutable: As mentioned earlier, symbols are immutable in the sense that once created, their value cannot be changed.
What does immutable mean in this context?
When we say that a primitive type is immutable, we mean that you cannot alter the value of the variable once it is set. For example:

If you modify a string or number, JavaScript creates a new string or number rather than modifying the original one.
If you change the value of a variable holding a primitive, it just points to a new value, but the original value remains intact.
What about objects and arrays?
Objects, arrays, and other non-primitive types in JavaScript are mutable, meaning their internal properties or elements can be changed even if the variable reference to the object or array remains the same. However, you can prevent mutation in some cases by using Object.freeze() or other methods.

In conclusion:
All the primitive types in JavaScript (String, Number, Boolean, Undefined, Null, and Symbol) are immutable in terms of their values. You cannot modify the value of a primitive once it is set; instead, any operation that seems to modify it will create a new value.







But it appears that when a new value is assigned to primitive type then the old value is lost because it is no more in the memory. E.g let x = 2; x =5; then 2 is lost.


You're absolutely right! When you assign a new value to a variable that holds a primitive type, the old value is effectively lost in the sense that the variable is now pointing to a new value in memory, and the previous value is no longer accessible through that variable.

How it works:
When a primitive value (like a number, string, boolean, etc.) is assigned to a variable, that variable holds a reference to the value in memory. In the case of primitive types, the value itself is stored directly in the variable. If you later assign a new value to that variable, the variable's reference changes to the new value, and the old value is no longer referenced by that variable. At that point, the old value is eligible for garbage collection if there are no other references to it.

Here's a simple breakdown of what happens:

Example:


let x = 2; // x holds a reference to the value 2 in memory
console.log(x);  // Output: 2

x = 5; // Now x holds a reference to the value 5
console.log(x);  // Output: 5

// The old value 2 is no longer referenced by x, so it is lost
What happens behind the scenes?
Initially, x is assigned the value 2. The value 2 is stored in memory.
When you assign x = 5;, the reference of x changes to point to the value 5. The value 2 is no longer referenced by x.
Since there is no other reference to the value 2, the garbage collector will clean it up eventually.
Key points:
Immutability of Primitives: The immutability of primitive values means that you cannot change the value of a primitive once it is created. However, you can reassign the variable to a new value, which makes the old value "lost" as it is no longer referenced.
Memory Management: The old value is not actually "deleted" immediately, but it becomes eligible for garbage collection. The memory used by the old value will be reclaimed once it is no longer referenced anywhere in the program.
This behavior is typical of how primitive values work in JavaScript: they are simple values that are copied by value, and the variable holding the value can be reassigned to another value, causing the original value to be "lost" if it is no longer referenced.







So, immutability is always about value of variable, not type. Should I think this?


Yes, you're on the right track! Immutability refers to whether the value associated with a variable can be changed, rather than the type of the variable itself.

Here’s the distinction to clarify:

Immutability: Value vs. Type
Immutability of Value:

Immutability means that once a value is assigned to a variable, it cannot be changed.
In JavaScript, primitive types (such as string, number, boolean, undefined, null, and symbol) are immutable because, once you assign a value to a variable, you cannot directly modify that value. Instead, you create a new value when performing operations on it.
For example:


let x = 2;      // The value 2 is immutable
x = 5;          // The variable x now holds the new value 5
// The value 2 is lost, but you can't change the value 2 itself once assigned
Immutability is Not About Type:

The type of a variable can be changed, but the immutability concept applies to the value itself, not the type.
In JavaScript, variables can be reassigned to different types. For example, you can assign a number to a variable and then assign a string to the same variable:


let y = 10;      // y is a number
y = "Hello";     // Now y is a string
However, the immutability concept would still apply to the values: you can't change the value 10 directly, and you can't modify the value "Hello" once assigned.
Example to Illustrate:
Primitive Value Immutability:



let str = "Hello";
str = str + " World";  // Creates a new string, "Hello World", and assigns it to `str`
console.log(str);  // "Hello World"
// The original value "Hello" is no longer in use, but it cannot be modified directly.
Mutable Objects:

Objects and arrays, on the other hand, are mutable. You can change the contents of an object or an array (even if you can't change the variable reference itself, you can change the object properties or array elements):


let arr = [1, 2, 3];
arr[0] = 10;  // Modifies the first element of the array
console.log(arr);  // [10, 2, 3]
Summary:
Immutability is about whether the value a variable holds can be changed or not, not the type of the variable.
Primitives in JavaScript (like numbers, strings, booleans, etc.) are immutable, meaning their values can't be modified directly once set.
Objects and arrays are mutable, meaning their internal properties or elements can be changed, but the reference to the object or array itself can also be reassigned.
So, yes, you can think of immutability as relating to the value that the variable holds, rather than the variable's type.

No comments:

Post a Comment

Hot Topics