开发者

In JavaScript, is '!=' the same as '!=='? [duplicate]

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

Possible Duplicates:开发者_StackOverflow中文版

Which equals operator (== vs ===) should be used in JavaScript comparisons?

What is the difference between != and !== operators in JavaScript?

Look at this commit:

Is != the same as !== in JavaScript?


They are subtly not the same.

!= checks the value
!== checks the value and type

'1' != 1   // false (these two are the same)
'1' !== 1 // true (these two are **not** the same).

In the previous example. The first half of the expression is a string, the second half is an integer.


From JavaScript syntax, Operators,

!== Not identical

!= Not equal

AND "Identical means equal and of same type."

From 5.4. Equality Operators:

"In JavaScript, numbers, strings, and boolean values are compared by value. ... On the other hand, objects, arrays, and functions are compared by reference. "

--

So in summary, are they the same? No, because there is an additional test with !== (over !=) for type sameness as well as equalness.


No, it is not the same. See for example here.

4 !== '4' returns true   (and 4 === '4' returns false)
4 != '4'  returns false  (and 4 == '4'  returns true)


The big difference is that != performs type coercion. That is, one value is effectively cast to the other before equality is checked. This is why, as in Amadiere's answer:

'1' != 1

evaluates to false. The same holds true for == v. ===. In general, avoid == and != unless you specifically want coercion to be performed. Use === and !== and check for exactly the result you're looking for.


It checks not only value, but also the type of the things compared.

This is also the same in PHP and some other languages too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜