Javascript is certainly a popular language these days. Unfortunately it has tons of razor-sharp edges that will rip your fingertips to shreds like scorpions on a ceramic knife. It's important to be on the watch for patterns that are common in other languages which can cause a lot of trouble in Javascript. This can happen especially if you switch between languages a lot.

The example du jour that I wanted to share is variable hoisting. This phenonemon (where variables are 'hoisted' to the 'top' of the function) is caused by Javascript's declaration of variables in a function scope, meaning that variables declared in a function are available anywhere in that function, even before they are assigned a value.

Ok, makes sense, the above code uses the variable 'n' that's created inside the function, which hasn't yet been assigned a value the first time it's printed. In many places you may not even notice, or get a big ol' undefined, which you can fix. But somewhere this can really screw you is in loops where you're closing over a variable that ends up being declared in function scope outside the loop. See the following example:

This example demonstrates that 'msg' is shared between the three invocations of 'alert'. Avoid this fate by getting in the habit of explicitly declaring the variables that your closure is closing over by passing them in as arguments and binding them at the time the closure is created, as below.

Successful programming is about releasing correct, useful features quickly. The more preventative habits you get into while using a hard-to-debug, dangerous language like Javascript, the happier you and your users will be.


Discuss this on hacker news.