console.log(x)
var x = 10;
The console gives me undefined but I was expected reference error
console.log(x)
var x = 10;
The console gives me undefined but I was expected reference error
var
is the old way of declaring a variable in JS. It has a few properties that you should consider in comparison to what let
and const
let you do.
Your variable declaration var x = 10
will be raised up to the top of the script, as a function declaration on the other hand is hoisted by the JS engine during compilation. However, ONLY the declaration is hoisted and the variable will be assigned undefined
until you assign to it another value manually using the assignment operator =
.
JS engine doesn't throw a ReferenceError
because your code is translated (using hoisting) into
var x;
console.log(x);
x = 10;
At the same time, var
doesn't have the concept of block scope, so at the same time the code below is running just fine
console.log(x);
{
var x = 10;
}
The code above is being translated (using hoisting) into
var x;
console.log(x);
{
x = 10;
}
If a variable is used in code and then declared and initialized, the value when it is used will be its default initialization (undefined
for a variable declared using var, use const
and let
to avoid this).