Variables & Constants in Node.js
Understand how variables and constants work in JavaScript: declaration, scope, hoisting, mutability, reassignment, and best practices.
Introduction to Variables
Variables are named containers used to store data so it can be reused and manipulated throughout a program.
1. What is a Variable?
Storing values in memory.
Declaring Variables
JavaScript provides three keywords to declare variables, each with different behavior.
1. var (Legacy)
Function-scoped declaration.
2. let
Block-scoped variable.
3. const
Block-scoped constant.
Mutability vs Reassignment
const prevents reassignment, not mutation.
1. Mutating const Objects
Allowed behavior.
Hoisting
Hoisting means JavaScript processes declarations before execution.
1. var Hoisting
Hoisted and initialized as undefined.
2. let / const Hoisting (TDZ)
Temporal Dead Zone.
Variable Scope
Scope determines the visibility and lifetime of a variable.
1. Block Scope
let and const.
2. Function Scope
var behavior.
Redeclaration & Reassignment
Different keywords allow different behaviors.
1. Redeclaration Rules
var vs let/const.
2. Reassignment Rules
const cannot be reassigned.
Best Practices
Following best practices avoids bugs and improves readability.
1. Recommended Guidelines
Industry standards.