DEV Community

sromelrey
sromelrey

Posted on

JavaScript Concepts: Declaration, Initialization, Mutability, Immutability and Reassignment

This blog is dedicated to understand the following JavaScript Concepts:

  • Declaration
  • Initialization
  • Mutability
  • Immutability
  • Reassignment

Declaration

This is the phase where you tell the JavaScript engine about the variable. For example:

 let age; 
Enter fullscreen mode Exit fullscreen mode

declares that there is a variable named age.

Initialization

This phase involves assigning a value to the variable. If you do not explicitly initialize the variable at the time of declaration, JavaScript automatically initializes it to undefined.

let a;
console.log(a);
Enter fullscreen mode Exit fullscreen mode

Output: undefined

Mutability

This refers to the ability to alter the internal state or content of a data structure or object in place. For example, if we have object obj and you changed a property within it, you would be mutating the object:

let obj = { key: "value" }; 
obj.key = "new value"; 
Enter fullscreen mode Exit fullscreen mode

Mutating the object by changing a property

Immutability

Immutability refers to the inability to alter the state or content of a variable after it has been created. When a variable holds an immutable value, any modification results in the creation of a new value rather than changing the original.

let greeting = "Hello";
let newGreeting = greeting.replace("H", "J");

console.log(greeting);      // Output: "Hello"
console.log(newGreeting);   // Output: "Jello"
Enter fullscreen mode Exit fullscreen mode
In this example:
  • greeting is a string with the value Hello.
  • The replace method creates a new string newGreeting with the value Jello.
  • The original greeting string remains unchanged.

Immutability ensures that primitive values remain constant, preventing unintended side effects. Any operation that attempts to modify an immutable value creates a new value, leaving the original unchanged.

Reassignment

This refers to the act of assigning a new value to a variable. This action doesn't alter the original value; rather, it updates what the variable points to.

let y = "hello"; 
y = "world";
Enter fullscreen mode Exit fullscreen mode

Reassigning y to reference a different string

Conclusion

In this topic, we explored key JavaScript concepts: declaration, initialization, mutability, immutability, and reassignment. Understanding these concepts helps in writing clear and predictable code.

  • Declaration introduces a variable.
  • Initialization assigns an initial value.
  • Mutability allows modification of an object's state.
  • Immutability prevents changes to a value, ensuring data integrity.
  • Reassignment updates the variable's reference without altering the original value.

Grasping these concepts is essential for effective JavaScript programming.

Top comments (0)