Thanks for sharing this information. It is a good explanation of why his code is undefined
. There is an important lesson here. Because of the globalThis
(window
for browsers) and variable hoisting, it is very possible to introduce dangerous bugs. For example, this very contrived example:
You can see that the variable i
is “hoisted” to the global scope in the test1()
and test2()
methods. This means that in the for
loop, because of lazy or sloppy coding, the loop only executes once and outputs really strange values.
This example is very contrived, but I wanted it to be easy to see what is going on. You should favor block scoped const
and let
in your modern javascript code. You should also learn about variable and function hoisting. I have seen some very dangerous bugs introduced because of interactions between methods where one of the methods accidentally hoisted a variable to the global scope causing hard to reproduce situations. :)