MediumVariable hoisting in JavaScript. Source: Variable hoisting in JavaScript | by Pravin M | Medium
Sitemap
Pravin M

Pravin M

I am a frontend developer with 10+ years of experience Blog :- https://www.frontendinterviewquestions.com

Member-only story

Variable hoisting in JavaScript

2 min readDec 25, 2023
Press enter or click to view image in full size
Variable hoisting in JavaScript
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…

--

--

Pravin M
Pravin M

Written by Pravin M

I am a frontend developer with 10+ years of experience Blog :- https://www.frontendinterviewquestions.com