Hacker News new | ask | show | jobs
by jaysoo 5840 days ago
> #13 In any code block, store local references to out-of-scope variables.

That doesn't even make sense. The for-loop block doesn't create a new scope, so it's perfectly valid to refer to the variable `a`. Plus, even if you create a new scope, you can still refer to `a` due to closure.

1 comments

We are talking about performance optimization here; which means 'what will work faster' over conventional approaches. Every time the scripting engine doesn't find a variable in the local scope, it starts searching for it upwards until it reaches global namespace. And this, my friend, costs CPU cycles. Now consider this out-of-scope variable being used in a loop. Closure is a power JavaScript has given us to use it wisely; and not to misuse.
In the case of closure, yes you will take a small performance hit. But the example given is still invalid because the only scope present is the function-scope (for-loop doesn't create new scope).

For example, if you ran the code below in FireBug you'll get the same results (minor variance aside).

function foo() { var a = 0; for (var i=0, j=a; i<10000000; i++) { var x = j+i; } }

function bar() { var a = 0; for (var i=0; i<10000000; i++) { var x = a+i; } }

(function() { var start = new Date().getTime(), end; foo(); end = new Date().getTime(); console.log(end-start); })();

(function() { var start = new Date().getTime(), end; bar(); end = new Date().getTime(); console.log(end-start); })();

for-loop does create a scope. In fact, every statement block is a scope in itself.

In your examples, just change the value of variable 'a' to 100 or 1000 and you will see the difference.

Blocks in JavaScript do not create scopes. This is different from many other languages (like Java or C).

In fact, Crockford has mentioned this as well: http://javascript.crockford.com/code.html

"JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages."

Which is why this code works:

(function() {

    for (var i=0; i<100; i++);

    alert(i);
})();

Notice the variable `i` is accessible from outside the for-loop.

That's correct. Thanks a lot. Updated the blog with the correct example (using function). I was testing on Chrome and even your examples showed better results with value of variable 'a' to 1000, although slightly. Firefox shows no difference.

Another thing, JavaScript 1.7 has introduced block level scopes.. you can achieve that by using the 'let' keyword instead of 'var' to declare a variable. Although most browsers don't support it yet.

No problem. It's one of those things developers don't realize when coming from C-style languages. :)