Understanding Hoisting in JavaScript- Variables and Functions
Understanding Hoisting in JavaScript- Variables and Functions
What is Hoisting?
Hoisting Variables
var Declarations
Explanation:
var myVar;
console.log(myVar); // undefined
myVar = 10;
console.log(myVar); // 10
Here, the declaration var myVar is hoisted to the top, but the
initialization myVar = 10 remains in place. As a result, the
first console.log prints undefined.
Variables declared with let and const are also hoisted, but
unlike var, they are not initialized until their definition is
evaluated. Accessing them before the declaration results in
a ReferenceError.
Hoisting Functions
Function Declarations
Explanation:
function greet() {
console.log('Hello, World!');
}
greet(); // Hello, World!
Function Expressions
Function expressions, whether assigned to a variable
using var, let, or const, are not hoisted in the same way. The
variable declaration is hoisted, but the function assignment
is not.
Explanation:
var greet;
greet(); // TypeError: greet is not a function
greet = function() {
console.log('Hello, World!');
};
Best Practices
2. Example:
function example() {
var myVar;
console.log(myVar); // undefined
myVar = 10;
console.log(myVar); // 10
}
1. Use let and const: Prefer let and const over var to
avoid the issues associated with variable hoisting
and to benefit from block scoping.
Example:
function example() {
console.log(myLet); // ReferenceError: Cannot access 'myLet' before initialization
let myLet = 10;
console.log(myLet); // 10
}
Conclusion