Jason Warner
1 min readFeb 4, 2020

--

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:

Contrived issue showing hoisting and an “unintended” bug

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

--

--

Jason Warner
Jason Warner

Written by Jason Warner

I enjoy everything related to code and being a dev. However, my only skills are showing up and being lucky and I'm not sure if luck is a talent.

No responses yet