News for hackers. Stuff that matters.
Re:Hide this in your coworkers' JavaScript code tomorrow by danielweber on Monday March 31, 2014 @09:52AM (#7501422)
I haven't had my morning coffee; can you explain what this breaks? I know JavaScript's scoping rules are unusual.
Re:Hide this in your coworkers' JavaScript code tomorrow by chewxy on Monday March 31, 2014 @10:04AM (#7501501)
Imagine you have inexperienced coders who do this:

    function foo() { 
        bar = function(){}; //define bar
    }

    function baz() {
        bar(); // use bar
    }
Note that both foo() and baz() could themselves, be inside another function. Doesn't really matter. Now `bar` is a defined as a a property of the global object.

If you add

    if (false) {
        var bar;
    }
in baz(), most developers, as I had noticed, will ignore it - afterall, it's a false condition, the code will never enter that branch. But because variables are "hoisted", you have now declared `bar`, it's lexically scoped as a new variable under `baz()`, with the value `undefined`.

So, when `bar()` gets called, it becomes an error, because `undefined` is not a function definition.

...

and yes, dear JavaScript developers, despite all the good efforts of people like Nicholas Zakas, Douglas Crockford, Addy Osmani and the like, bad JavaScript still exists in the wild. And I feel, in greater numbers than ever, and I am not optimistic that the amount of bad JavaScript will be ever reduced. This depresses me. Can't be helped, I guess.

Re:Hide this in your coworkers' JavaScript code tomorrow by mr_tophat on Monday March 31, 2014 @04:21PM (#7503860)
If this is the inexperienced way of doing this, what would be the correct way?
Re:Hide this in your coworkers' JavaScript code tomorrow by zupa-hu on Monday March 31, 2014 @10:15AM (#7501560)
It is only harmful if the developer actually used the variable as a side effect, aka relied on it outside the current scope.

By making the global variable local to the scope around the if statement, side-effects won't escape the local scope (as said, the if block does not declare a new scope).

Re:Hide this in your coworkers' JavaScript code tomorrow by brianchu on Monday March 31, 2014 @09:59AM (#7501471)
I'm not too sure either. In JS, block scoping does not exist. There are only function scopes, so the var declaration gets hoisted out of the if block (but the assignment occurs in the if block - so the assignment doesn't happen).
Re:Hide this in your coworkers' JavaScript code tomorrow by chewxy on Monday March 31, 2014 @10:18AM (#7501581)
Oh you can definitely fake block scoping in JavaScript, with ES5. ;P