notoriousb1t

The Answer is 'IFFY'

The biggest pet peeve I have with JavaScript is how it handles local variable declarations.  In most modern languages, a local variable can only be used within the block of code it is defined.  In JavaScript, the local variable can be used anywhere within the function.

What's the difference?

for (var i = 0; i < 5; i++) {  
   // ...
}
Console.WriteLine(i);  
// compiler error, i is not defined

for (var i = 0; i < 5; i++) {  
   // ...
}
console.log(i);  
// prints '5'

The JavaScript code above will print the number 5 to the console, since it 'i' is visible. If the JavaScript code is not inside another function, the variable 'i' will also be attached to the window. You can imagine what kind of havoc this can wreak on a large application. Here is a more honest version of what that JavaScript snippet ends up being after variable hoisting:

var i;  
for (i = 0; i < 5; i++) {  
   // ...
}
console.log(i);  
// prints '5'

The common work around for this is an Immediately Invoked Function Expression.  An IIFE (pronounced "iffy"), takes care of the problem by first, declaring a function inline wrapped by parenthesis, then immediately calling it. Here is an example:

(function() {
    for (var i = 0; i < 5; i++) {
        // ...
    }
})();
console.log(i);  

The above code will throw the error Reference Error: i is not defined because variable 'i' is no longer visible to the line with console.log(i). Here are some of the variations of an IIFE:

(function() {
   // style 1
})();

(function() {
   // style 2
}());

-function() {
   // other styles use an operator 
   // to indicate a function expression
   // this example uses minus and returns a NaN
}();

While this workaround keeps your code safe from itself, it makes a big, ugly mess of JavaScript files. As an evangelist for readable code over performance, I really dislike function variable scoping.

It forces a programmer choose safety over readability.