Friday, October 28, 2016

JavaScript (JS) and block level variables and closures

Be careful when dealing with JavaScript (JS) block level variables. JS block level variables don't follow our intuition when they are paired with closures.

For example, imagine a for loop which instantiates a new local variable c in each iteration. Now, imagine that you increase the value of that variable c by 1 in each iteration. If you would like to print c to output console, 500ms after each increment, you would probably expect all iterations to have different values, right? However, what will happen is that all the print outs will contain the very same value.


In order to get a true block level variable in JS, we should enclose the iteration code in an anonymous function. This way, each anonymous function comes with its own scope, and closures (and setTimeout construct is a closure), will print correct (different) values.

Here is the example:






No comments:

Post a Comment

Ubuntu 12.04, 14.04, 16.04 - auto start an app or script before login

To run a command or application at startup, even before the user has logged in, you can use this file: /etc/rc.local The commands entered...