Why does this code snippet give the error "Uncaught ReferenceError: x is not Defined" in the console
<body> <script> console.log(x); </script> <script> var x = 10; </script> </body>
And this record is "Undefined"?
<body> <script> console.log(x); var x = 10; </script> </body>
I'm trying to understand variable declaration and variable scope. And expect boosting to happen since the entire code is in the same page. But because the console.log() is separated in another script tag, I get an error instead of just logging "undefined" in the console.
var
is promoted, which means it can be accessed at the beginning of the scope in which it is defined, even though the declaration line may be at the end of the scope. If you access the var before declaring it, it isundefined
because you still need to perform the declaration and possibly initialize the variable to a specific value. So that's how your second example works.Read about boosting here:
https://developer.mozilla.org/en-US/docs/glossary/lifting
But in the first example 2
has 2 different scopes, so the var basically doesn't exist in the first script, hence the errornot Defined
.Learn about
var
and its scope here:https://developer.mozilla.org /en-US/docs/Web/JavaScript/Reference/Statements/var
important I strongly advise against using
var
. Please useconst
andlet
instead. Using var for promotion can lead to errors that are sometimes difficult to debug and fix. If you need to use onlyvar
in production, just use esbuild to downgrade your code to the appropriate older version of JS.Interestingly,
const
andlet
are also somewhatelevated, but accessing them in an elevated state causes a runtime error (this is called a transient dead zone), which is why they are safer because you get the error immediately, rather than silently raisingvar
, leaving you with a potential error that you don't know about.About the temporal dead zone:
https://developer.mozilla .org/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz