scotthmurray / d3-book

Code examples for “Interactive Data Visualization for the Web”
http://d3book.com
Other
2.41k stars 1.79k forks source link

Chapter 3 scope clarification (AKA who will gotcha the gotchas?) #49

Open jordy248 opened 3 years ago

jordy248 commented 3 years ago

The "Function-level scope" section of Chapter 3 (second edition, accessed on O'Reilly) mentions the following:

With block-level scope, our i would exist only within the context of the for loop, for example, so any attempts to read the value of i or change i outside of the loop would fail. This is nice because you could establish other variables from within your loop and know that they wouldn’t conflict with variables that exist elsewhere.

Because we used var to declare the i variable in the for loop, i gets attached to the window (hey! that's the next section! 😄), so we actually could access it outside of the for block:

image

Compare this with declaring the variable with let:

image

This is horrible JS minutia that's absolutely outside the scope of this section's objectives, but it's caused me grief in the past, so I figured I'd point it out.