Understanding Mutability vs. Immutability in JavaScript
Understanding Mutability vs. Immutability in JavaScript
Main Concept
In JavaScript, mutability refers to the ability of an object to be changed after its creation, while immutability means that once an object is created, it cannot be changed.
Key Concepts
Mutable Data Types
- Definition: Objects and arrays are mutable.
- Characteristics: You can change their content without creating a new object.
Example:
let obj = { name: "Alice" };
obj.name = "Bob"; // This changes the existing object
console.log(obj); // Output: { name: "Bob" }
let arr = [1, 2, 3];
arr.push(4); // Modifies the existing array
console.log(arr); // Output: [1, 2, 3, 4]
Immutable Data Types
- Definition: Primitive data types (like strings, numbers, booleans) are immutable.
- Characteristics: When you change a primitive value, a new value is created instead of changing the existing value.
Example:
let str = "Hello";
str[0] = "h"; // This does not change the original string
console.log(str); // Output: "Hello"
let num = 42;
num += 1; // Creates a new number instead of modifying the existing one
console.log(num); // Output: 43
Summary
- Mutability allows objects and arrays to be changed without creating a new instance.
- Immutability means that primitive values cannot be altered; any change results in a new value.
- Understanding these concepts is crucial for effective programming in JavaScript, especially for state management in applications.
By grasping the difference between mutable and immutable data types, beginners can write more predictable and maintainable code.