JavaScript variables are fundamental to programming, acting as containers for storing data values. Historically, var
was the only way to declare variables. However, with the introduction of ECMAScript 2015 (ES6), let
and const
were introduced to address shortcomings of var
, particularly concerning scoping and mutability. Understanding the differences between these three keywords is crucial for writing modern, maintainable, and error-free JavaScript code.
Before we start understanding JavaScript variables and constants, let us first understand one important term that we are going to use again and again in our further discussion.
What is Hoisting?
Hoisting is a fundamental JavaScript mechanism where variable and function declarations are conceptually moved to the top of their containing scope during the compilation phase, before code execution.
This means that regardless of where variables and functions are declared, they are processed first. However, the exact behavior of hoisting differs significantly between var
, let
/const
, and functions.
The Legacy Keyword: var
The var keyword is the oldest way to declare a variable in JavaScript.
Scope of var.
Variables declared with var are function-scoped or globally-scoped. This means a var declared inside a function is only available within that function. If declared outside any function, it is global. Crucially, var ignores block scope (blocks defined by curly braces {}, such as in if statements or for loops).
JavaScript Example Code:
function exampleVarScope() { if (true) { var x = 10; } console.log(x); // Output: 10 (var ignores block scope) } // console.log(x); // Throws ReferenceError: x is not defined (x is function-scoped)
Hoisting of var
Variables declared with var
are hoisted to the top of their scope (function or global). However, only the declaration is hoisted, not the initialization. This leads to a behavior where you can use a var
before it is declared in the code, but its value will be undefined
.
JavaScript Example of var Hoisting.
console.log(a); // Output: undefined var a = 5; console.log(a); // Output: 5
The Modern Standard: let
Scope of let
function exampleLetScope() { if (true) { let y = 20; console.log(y); // Output: 20 } // console.log(y); // Throws ReferenceError: y is not defined (y is block-scoped) }
Hoisting of let
// console.log(b); // ReferenceError: Cannot access 'b' before initialization (TDZ in effect) let b = 15; console.log(b); // Output: 15
let count = 1; count = 2; // Allowed console.log(count); // Output: 2
The Constant Keyword: const
Scope and Hoisting of const
const PI = 3.14159; // PI = 3.14; // Throws TypeError: Assignment to constant variable.
const
variable itself cannot be reassigned to a different value, if the value is an object or array, the contents of that object or array can be mutated.const user = { name: "Alice" }; user.name = "Bob"; // Allowed: Object property modification console.log(user.name); // Output: Bob const numbers = [1, 2]; numbers.push(3); // Allowed: Array mutation // numbers = [4, 5]; // NOT Allowed: Reassignment of the const variable
- Use const by default for any variable that won't be reassigned. This prevents accidental changes and makes the code's intent clearer.
- Use let for variables that need to be reassigned (e.g., loop counters, variables holding a state that changes).
- Avoid using var completely due to its confusing scope and hoisting behavior.
No comments:
Post a Comment