jslint-error-explanations icon indicating copy to clipboard operation
jslint-error-explanations copied to clipboard

Explain "Unexpected 'typeof"

Open senseysensor opened this issue 11 years ago • 4 comments

JSLint: Unexpected 'typeof'. Use '===' to compare directly with undefined.

Debatable message. undefined is not real keyword and can be easily reassigned. Shouldn't I compare with typeof instead?

senseysensor avatar May 15 '13 11:05 senseysensor

JSLint used to enforce typeof "undefined" check always, but it changed to undefined comparison.

Douglas Crockford is against old style. Once upon a time, old styles were necessary, but times have changed. For example, the old style of embedded scripts used to be:

<script language="JavaScript" type="text/javascript">
    <!--
    ...
    //-->
</script>

But now, Crockford prefers the modern style:

<script>
    ...
</script>

http://javascript.crockford.com/style1.html http://javascript.crockford.com/script.html

A similar modernization of style has occurred with undefined comparison. ES5 guarantees that undefined is undefined. In strict mode, in comparison with the old and new styles, the typeof "undefined" check is longer to type and is no longer necessary now that undefined can be compared directly.

See the JSLint discussion: https://plus.google.com/101248256976407044060/posts/Q5oFnnxG9oL

Crockford basically says that typeof "undefined" check is longer and slower and is unnecessary.

XP1 avatar May 22 '13 12:05 XP1

@XP1 - You could write that up into a full article and submit it as a pull request! If you'd rather not, I will get around to adding a page for this message at some point in the near future.

jamesallardice avatar May 22 '13 12:05 jamesallardice

ESLint no-undefined rule enforces the reverse of it.

Because undefined can be overwritten or shadowed, reading undefined can give an unexpected value

Therefore typeof foo === "undefined" check is preferred over foo === undefined

armujahid avatar Jun 06 '18 06:06 armujahid

Hi team, this is old but I've found this issue and still don't get why JSLint outputs this as wrong code: typeof data !== "undefined" If the variable data isn't defined and I simply do a check as JSLint says like this: data === undefined I will get an uncaught error. That's why I use typeof to check. Does that make sense?

Thank you!

brunorilla avatar Aug 17 '21 13:08 brunorilla