Hacker News new | past | comments | ask | show | jobs | submit login

I'd like to have a guide for writing code that is easily optimized by V8 and similar engines. Having local variables is good, as far as I can tell, but it would be nice to have a full overview with dos and don'ts



"Having local variables is good"

Reading sentences like this scare me because it reminds me that some people don't know what the 'var' keyword means or think it's acceptable to shove everything in window or global.


Last I read, JavaScript has 2 scopes: function scope, and global scope. Unlike many languages, there is no block scope (e.g. a counter in a for loop).



It's definitely not available in current JavaScript interpreter in different browsers.


On the other hand, JavaScript allows you to nest functions, unlike many languages.


I feel dumb now because I fear I don't understand what you mean when you say block scope...

    for(var i=0; i<3; i++) { console.log(i); }
appears to be valid... (or just in Chrome?)


Valid, just doesn't do what you think.

function foo() { var x = 1; if (true) { var x = 2; var y = 3; } console.log(x); console.log(y); }

foo(); // 2, 3 (vs 1, undefined if there was block scope)


Thanks for the explanation!


JS performs "variable hoisting", so your example is interpreted as:

    function(){ var i; … for(i=0; …
It has surprising side effects:

    alert(i);
    var i;
works and outputs "undefined", which is value of the variable i that is defined.

    alert(k);
    var i;
This is an error, and will fail to execute because of undefined variable.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: