When creating a variable such as var three = 3;
do JavaScript interpreters first assign var three;
then three = 3;
or is it done all in one shot?
The part that is of interest to me here is the potential intermediate undefined
value and a way, if possible to observe that process.
Edit
New Title: Does variable declaration happen before variable initialization
Given this one line JavaScript File
var three = 3;
Does the interpreter still hoist the variable three and effectively change this to
var three;
three = 3;
w3schools has a good article explaining this in some detail.
All JavaScript variables are hoisted, as @fardjad mentioned. They are also initially set to be
undefined
.To show this, consider the following:
This is the equivalent to this:
No JavaScript interpreter to my knowledge would be smart enough to realize that the
three
variable isn't needed before it's declared and initialized. If it weren't hoisted, theeval
code would throw an error.