开发者

javascript, strange comparison operator [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Javascript === vs == : Does it matter which “equal” operator I use?

I've met "!==" strange com开发者_如何学运维parison operator in source code of some chrome extension. Code snippet:

function closedTab(id) {
   if (openedTabs[id] !== undefined) {
      openedTabs[id].time = timeNow(0);
      closedTabs.unshift(openedTabs[id]);
   }
}

This operator is not used just once, so there's should some meaning.

Is "!==" came from some JavaScript magic? Or it's just equivalent to usual "!="? Thanks


The difference is that !== doesn't try to convert its operands to the same type before comparing. Same with === and ==.

See this question: Difference between == and === in JavaScript


!== is the not identity comparison operator.

!= will coerce the two types to match

!== will not coerce the two types

For a few examples:

3 == "3"    // true - the operands are coerced to the same type, then compared and they match
3 === "3"   // false - the operands are not coerced to the same type, so do not match
3 != "3"    // false
3 !== "3"   // true


This is called a strict comparison operator where it not only checks for value but also for type.


The difference comes from what happens when values are of different type.

The !== operator (and its cousin ===) checks on the equality of both value and type. != and == on the other hand try to coerce values to be the same before checking equality.

For example:

if(5 === "5")      // evaluates to false
if(5 == "5")       // evaluates to true

The same concept is extended to != and !==


It's an identical comparison operator. It compares value and type. For example:

if('foobar' == true) // true
if('foobar' === true) // false
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜