These are 2 examples which must have attained same result:
Example 1
<script>
console.log(a);
var a = 10;
console.log(a);
</script>
<script>
var a = "";
console.log(a); //will result undefined
a = 10;
console.log(a); //will result 10
</script>
undefined
10
Example 2
<script>
console.log(a);
a = 10;
console.log(a);
</script>
<script>
var a = "";
console.log(a); //should result undefined
a = 10;
console.log(a); //should result 10
</script>
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