§2023-08-14
♠ const, let and hoisting
♠ const and let is preferred over var
In JavaScript, const is a keyword used to declare a variable that has a constant value. Once a variable is declared using const, its value cannot be changed or reassigned. It provides a way to define variables that are meant to remain constant throughout their scope. Here's the basic syntax of using const:
const pi = 3.14159; // you must assign a value to the const variable
const greeting = "Hello, world!";
- Key points to remember about const:
- Immutable Value: The value assigned to a const variable cannot be modified after the initial assignment. This means you cannot reassign a new value to a const variable once it has been declared.
- Block Scope: Like let, const is block-scoped. It means the variable's scope is limited to the block (usually defined by curly braces {}) in which it is declared.
- Hoisting: Like let, const is also hoisted to the top of its scope but is not initialized until the actual declaration.
- Assignment During Declaration: When using const, you must assign a value to the variable during its declaration.
- Unlike let, you cannot declare a const variable without initializing it.
- Object and Array Properties: While a const variable itself cannot be reassigned,
- it doesn't make the object or array it references immutable. You can modify the properties of objects or elements of arrays declared using const,
- but you can't reassign the entire object or array to a new value.
const number = 42;
console.log(number); // Output: 42
number = 99; // This will result in an error since you can't reassign a const variable
const person = {
name: "Alice",
age: 30
};
person.age = 31; // This is allowed, as you're modifying a property of the object
person = { name: "Bob", age: 25 }; // This will result in an error
Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the actual code execution takes place. This means that you can use a variable before it's formally declared in your code, but there are some important nuances to consider.
- For
var
declarations, hoisting has a significant impact because variables declared with var are automatically initialized to undefined at the top of their scope during hoisting. This can lead to unexpected behavior and bugs.
However, with let and const declarations, hoisting works slightly differently. Let's break down the behavior:
- Hoisting: Both let and const declarations are hoisted to the top of their scope. This means that even if you declare a let or const variable later in your code, its declaration is effectively moved to the top of its containing scope.
- Temporal Dead Zone (TDZ): Unlike var, where variables are initialized with undefined during hoisting, let and const declarations are not initialized during hoisting. Instead, they enter what's known as the "Temporal Dead Zone" (TDZ). The TDZ is a phase in the code where you cannot access the variable before its actual declaration. Accessing the variable in the TDZ results in a ReferenceError.
- Initialization: Variables declared with let and const are only initialized when the actual declaration statement is encountered during the normal flow of execution. This means that you cannot use these variables before their declaration in the code.
Here's an example to illustrate this behavior:
console.log(name); // This will throw a ReferenceError in strict
let name = "Alice"; // Variable declaration is hoisted, but not initialized yet
console.log(name); // Output: "Alice"
In summary, while let and const declarations are hoisted to the top of their scope, they are not initialized during hoisting. They enter the TDZ and can only be accessed after their actual declaration in the code. This behavior helps catch potential bugs related to variable usage before their declaration.
♠ var is not block-scoped; it has function-level scope or global scope, depending on where it's declared. This behavior can sometimes lead to unexpected and confusing results in your code.
-
When you declare a variable using var inside a function, that variable is accessible throughout the entire function, regardless of where it's declared. This is different from let and const, which have block scope and are only accessible within the block (enclosed by curly braces) in which they are declared.
-
Here's an example to illustrate the difference between var and let in terms of scoping:
function example() {
if (true) {
var varVariable = "I am a var variable";
let letVariable = "I am a let variable";
}
console.log(varVariable); // Outputs: "I am a var variable"
console.log(letVariable); // Throws an error (letVariable is not defined)
}
To summarize:
var has function-level scope or global scope. let and const have block scope, which makes them safer and more intuitive to use in modern JavaScript development.