DEV Community

Discussion on: JavaScript Scopes

Collapse
 
jmourtada profile image
Jonathan Mourtada • Edited

The cost of this is added complexity to the language

One can argue about this :) I would say that let and const makes Javascript simpler and that var adds complexity to the language. Most developers expects variables to be blocked scoped. But then again you should really learn the language first and then the concept function scope shouldn't be a problem.

I'm using a linting rule to disallow the use of var in my code base because i see no advantage of using it.

On more case that is tricky with var is when deferring execution.

var functions = [];
for (var i=0;i<3;i++) {
    functions[i] = function() {
        console.log(i);
    }
}

functions[0](); // 3
functions[1](); // 3
functions[2](); // 3
Enter fullscreen mode Exit fullscreen mode
Collapse
 
xiaohuoni profile image
xiaohuoni

var functions = [];
for (var i=0;i<3;i++) {
functions[i] = function(i) {
console.log(i);
}(i)
}

functions0; // 0
functions1; // 1
functions2; // 2