Member-only story
Variable hoisting in JavaScript
Source: Variable hoisting in JavaScript
For more questions and answers visit our website at Frontend Interview Questions
Variable hoisting is a behavior in JavaScript where variable declarations are moved to the top of their respective scope, regardless of where the actual declaration occurs in the code. This means that variables can be used before they are declared, but they will have an initial value of undefined.
Here’s an example of variable hoisting:
function foo() {
console.log(x); // logs 'undefined'
var x = 10;
console.log(x); // logs '10'
}
foo();In this example, we’ve defined a function foo that logs the value of variable x before and after it is declared and assigned a value of 10. Even though x is used before it is declared, JavaScript will hoist the declaration to the top of the function, so it will be available throughout the function with an initial value of undefined.
It’s important to note that variable hoisting only applies to variable declarations, not to variable assignments. This means that if you try to use a variable before it is declared and assigned a value, you will still get a ReferenceError.
Here’s an example:
function bar() {
console.log(y); // ReferenceError: y is not…








