Peterson Peterson - 3 months ago 11
Javascript Question

javaScript hoisting not working properly

These are 2 examples which must have attained same result:


Example 1


<script>
console.log(a);
var a = 10;
console.log(a);
</script>


Rendered

<script>
var a = "";
console.log(a); //will result undefined
a = 10;
console.log(a); //will result 10
</script>


Result

undefined
10



Example 2


<script>
console.log(a);
a = 10;
console.log(a);
</script>


Expectation of Rendering

<script>
var a = "";
console.log(a); //should result undefined
a = 10;
console.log(a); //should result 10
</script>


Result

enter image description here

Now, as per JS Hoisting in Scenario 2, the variable if not declared must have been automatically declared onto top of its scope and still result should have been the same. Why is it not? Where is the concept failed?

Answer

The second case is different, because

a = 10

... does not declare a hoisted variable. It creates a property in the window object (even if the code would have been inside a function). This is not a declaration, and thus something that is not hoisted. So before you create that property, it does not exist.

Note that what you listed as rendered code is not entirely correct. A hoisted variable does not get a value, so for your first example it should look like this:

var a; // undefined!
console.log(a); //will result undefined
a = 10;
console.log(a); //will result 10

Note that if this code is not part of a function body, var a also creates the window.a property, and this happens at the hoisted declaration.

And for your second example:

console.log(a); // does not exist. 
window.a = 10;
console.log(a); //should result 10
Comments