Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Explain "Unexpected 'typeof" #10

Open
senseysensor opened this issue May 15, 2013 · 4 comments
Open

Explain "Unexpected 'typeof" #10

senseysensor opened this issue May 15, 2013 · 4 comments

Comments

@senseysensor
Copy link

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?

@XP1
Copy link

XP1 commented May 22, 2013

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.

@jamesallardice
Copy link
Owner

@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.

@armujahid
Copy link

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

@brunorilla
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants