Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSLint complains about redefining undefined

undefined is technically able to be redefined, so it is not a reserved word. As a result, I usually write code in an anonymous function that forces undefined to be an undefined variable, as so:

(function (undefined) {
    "use strict";
    var o = {
        test: "testvalue"
    };
    if (o.test === undefined) {
        // Do stuff here
    } else {
        // Do other stuff there
    }
}());

However, JSLint mentions the following error:

Problem at line 1 character 15: Expected an identifier and instead saw 'undefined' (a reserved word).

Why does JSLint complain about undefined being an reserved word, when code can arbitrarily redefine the variable? I know that you can use typeof x === "undefined"; I just wanted to see why this method wouldn't work.

like image 935
kevinji Avatar asked Nov 17 '11 23:11

kevinji


2 Answers

'undefined' was declared an immutable property of the global object in ECMA-262 Edition 5 Section 15.1.1.3, published in December 2009.

By using 'undefined' as a parameter name in a function, you are attempting to mutate it with whatever is passed to the function. So technically, the error lies with browsers being slow to adopt the standard, and JSLint is correct.

like image 64
qwdk Avatar answered Oct 18 '22 10:10

qwdk


Your method does work. Just because JSLint doesn't like it doesn't make it a cardinal sin.

Try JSHint instead (for more sanity).

like image 25
James Avatar answered Oct 18 '22 10:10

James