Monday, February 14, 2022

var vs. let

If you declare a variable using let within a block, then it's locally scoped to that block (see note). For example, everytime you go through a loop, Javascript creates a new stack frame if you have locally scoped variables declared in that block. If you have an asynchronous event going on within that block, then the async code that runs later can safely refer to that variable without worrying that it's changed by another iteration of the loop.

By contrast, var declarations are scoped to the entire function so even if you declare it further down in the code, it's as if you declared it at the top of the function because of hoisting. With var variables, since there's only one instance of that variable for the whole function, then when your async code runs, it has to be concerned that the variable may have been changed by iterations of the loop that have already run. That's when you have to put in a closure. Note: A block is created by enclosing braces.

Image: Charlie Harutaka

Post a Comment

Note: Only a member of this blog may post a comment.