-1
console.log(x)
var x = 10;

The console gives me undefined but I was expected reference error

  • 4
    That's how `var` works - it has range of quirks like this. `let` and `const` fix these, with them, you'd get the error you expect. – FZs Oct 23 '21 at 09:54
  • 5
    See e.g. https://developer.mozilla.org/en-US/docs/Glossary/Hoisting. Unlike `let`, `var` has no _temporal dead zone_. – jonrsharpe Oct 23 '21 at 09:55
  • Please see [Are variables declared with let or const hoisted?](/q/31219420/4642212), [What is the temporal dead zone?](/q/33198849/4642212), [Javascript function scoping and hoisting](/q/7506844/4642212). – Sebastian Simon Oct 23 '21 at 10:25

2 Answers2

2

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;
}
netlemon
  • 964
  • 8
  • 22
0

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).