๐ท๏ธ Variables
In JavaScript, variables are used to store data. To create variables, the following three main keywords are used: var, let, and const.
1. var (ES5)
- Before ES6 (2015), var was used to declare variables.
- var is function-scoped, meaning it is accessible only within the function where it is declared.
- var is subject to hoisting. This means it is moved to the top of the code, but its value will be undefined until the actual declaration.
Example:
console.log(name); // undefined
var name = 'John';
console.log(name); // 'John'
Functional Scope:
function test() {
if (true) {
var x = 10;
}
console.log(x); // 10
}
test();
Issues:
- Hoisting can confuse the program's logic.
- Block boundaries are not respected, which can cause problems.
2. let (ES6)
- let was introduced in ES6 (2015).
- let is block-scoped, meaning it is accessible only within the block {} where it is declared.
- let is hoisted but is not assigned as undefined.
Example:
console.log(name); // ReferenceError: Cannot access 'name' before initialization
let name = 'John';
console.log(name); // 'John'
Block Scope:
function test() {
if (true) {
let x = 10;
}
console.log(x); // ReferenceError: x is not defined
}
test();
Advantages:
- Clearer scope
- Avoids hoisting-related issues
3. const (ES6)
- const was also introduced in ES6 (2015).
- const is block-scoped, like let.
- The value of a const-declared variable cannot be reassigned.
- However, if the variable is an object or array, its contents can be modified.
Example:
const name = 'John';
name = 'Jane'; // TypeError: Assignment to constant variable
Modifying Object Content:
const person = { name: 'John' };
person.name = 'Jane'; // allowed
console.log(person.name); // 'Jane'
Advantages:
- Fixed value prevents accidental reassignments
- Safer and more predictable code
Differences and Comparison
| Feature | var | let | const |
| Block Scoping | โ | โ | โ |
| Function Scoping | โ | โ | โ |
| Hoisting | โ (undefined) | โ (ReferenceError) | โ (ReferenceError) |
| Reassignment | โ | โ | โ |
| Initial Value Required | โ | โ | โ |
Hoisting Details
var is hoisted but initialized as undefined.
let and const are hoisted, but their values are not accessible until declared, resulting in a ReferenceError.
console.log(a); // undefined
var a = 5;
console.log(b); // ReferenceError
let b = 5;
console.log(c); // ReferenceError
const c = 5;
You can read more here