Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jslint claims variable is already defined? (1)

function wrapper() {
    var $R = {};

    $R.expandFont = function (direction, max_time) {
        // wtf? $R jslint error
        var self = this,
            el_prim = self[0],
            $R = {};

        alert(direction + max_time + el_prim + $R);
    };
}

This snippet gives error:

line 573 character 13
'$R' is already defined.

I think it is clear that it has not been previously defined.

$R was defined in the outer scope, but this should not be relevant. I should be able to define a local variable with the same name as JavaScript ( the language ) is function scoped. Yes, I know it is not block-scoped, but it is function scoped.

It is basic scoping rules. What gives?

Is this a jslint bug?

like image 491
please_delete_my_account Avatar asked Jan 12 '23 20:01

please_delete_my_account


1 Answers

This is a new feature in JSLint. It was added by a commit on 24 July 2013. The following example demonstrates the cause of the error:

(function () {
    var a = 1; // This declaration...
    return function () {
        var a = 2; // ... is shadowed by this one.
    };
}());

It appears that the warning is only issued when JSLint encounters a variable declared in function scope (not in the global scope) that is later shadowed (which may explain why commenters on your question were unable to reproduce it).

It appears that currently there is no way to turn off this warning.

Crockford has the following to say about this new warning:

JSLint now warns when a var is defined that has the same name as something in the outer scope. This is confusing because the reader cannot easily tell which variable he is looking at. It is sometimes an error because the new variable is accidentally hiding the old one. In some cases, the old one is the one intended.

I will get a page fully explaining this up on http://jslinterrors.com as soon as I get a chance.

like image 159
James Allardice Avatar answered Jan 23 '23 00:01

James Allardice