简体   繁体   中英

In JavaScript, is there any difference between typeof x == 'y' and typeof x === 'y'?

I'm aware of the difference between strict and loose comparison operators. Clearly x == y is different from x === y . But whenever I see code that uses typeof , it always uses === .

If the typeof operator always evaluates to a string (such as 'boolean', 'number', etc.), then wouldn't typeof x == 'y' and typeof x === 'y' always render the same result? And if so, why the use of === ?

I know it's faster doing strict comparisons, but except in extreme cases, the performance gain should be imperceptible. Another idea is that it's just clearer to always use === since it does cause issues with similar operations like x == undefined versus x === undefined . Is it worthwhile to reduce these cases to == to improve minification and transfer encoding, or is it better to keep === to maintain runtime performance and general clarity?

It makes absolutely no useful difference either way in this case.

The typeof operator returns a string indicating the type of the unevaluated operand.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

We know it is always going to be a string, and it will only be that of a few predefined values, so there is no explicit reason to use the strict operator when comparing the results of typeof, however the strict comparison operator should be used for readability, and to avoid any possible exceptions to that statement.

But

Loose equality using ==
Loose equality compares two values for equality, after converting both values to a common type.

That being said it should be marginally faster to use the strict comparison as there is no conversion, but the difference is so small that it doesn't matter, and micro optimizing is a very bad thing


Edit

According to the documentation 11.9.3 and 11.9.6 if they are the same type there should be no difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM