Hoisting in JavaScript
- Hoisting is a JavaScript behavior where variable and function declarations are processed before the code is executed. Because of hoisting, a variable or function can sometimes be accessed before its declaration appears in the code.
However, var, let, and const behave differently during hoisting.
For example:
console.log(a);
var a = 10;
The above code does not give an error. JavaScript treats it approximately like this:
var a;
console.log(a);
a = 10;
Therefore, the output is:
undefined
let and const are also hoisted, but they cannot be accessed before their declaration. The time between entering the scope and reaching the declaration is called the Temporal Dead Zone (TDZ).
console.log(a);
let a = 10;
This gives a ReferenceError.
Function declarations are also hoisted, so they can be called before they are written in the code.
function greet() {
console.log("Hello");
}
Output:
Hello
Scope in JavaScript
- Scope determines where a variable can be accessed and visibility in a JavaScript program.
- JavaScript mainly has Global Scope, Function Scope, and Block Scope.
Global Scope
A variable declared outside a function or block has global scope. It can generally be accessed from different parts of the program.
let name = "John";
function student() {
console.log(name);
}
student();
Here, name is declared outside the function, so it can be accessed inside the function.
Function Scope
A variable declared inside a function can be accessed only within that function.
function student() {
let age = 20;
console.log(age);
}
student();
Here, age is available inside the student() function.
It cannot be accessed outside the function:
function student() {
let age = 20;
}
console.log(age);
This produces a ReferenceError because age exists only inside the function.
The var keyword is function-scoped.
function student() {
var name = "John";
}
console.log(name);
Here, name cannot be accessed outside the function.
Block Scope
A block is code written inside { }. Variables declared with let and const are block-scoped, which means they can be accessed only inside the block where they are declared.
function student() {
let name = "John";
{
let name = "David";
console.log(name);
}
console.log(name);
}
student();
Output:
David
John
The inner name belongs to the inner block, while the outer name belongs to the function scope.
const also follows block scope.
{
const age = 20;
console.log(age);
}
Here, age can be accessed inside the block but not outside it.
Scope Difference Between var, let and const
| Keyword | Scope | Redeclaration | Reassignment |
|---|---|---|---|
var |
Function scope | Allowed | Allowed |
let |
Block scope | Not allowed in same scope | Allowed |
const |
Block scope | Not allowed in same scope | Not allowed |
Top comments (0)