开发者

Why 3 equal symbols in boolean comparisons? [duplicate]

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

Possible Duplicate:

Javascr开发者_如何学编程ipt === vs == : Does it matter which “equal” operator I use?

Why do I see lots of javascript code lately with expressions that look like this:

if(val === "something")

Why "===" instead of just "=="? What's the difference? When should I use one or the other?


The === does not allow type coercion, so something like this would return false:

if (2 === '2') // false

The "normal" javascript == operator does allow type coercion, and so this would return true:

if (2 == '2') // true


var a = 3;
var b = "3";

if (a == b) {
  // this is true.
}

if (a === b) {
  // this is false.
}


=== is typically referred to as the identity operator. Values being compared must be of the same type and value to be considered equal. == is typically referred to as the equality operator and performs type coercion to check equality.

An example

1 == '1' // returns true even though one is a number, the other a string

1 === '1' // returns false. different datatypes

Doug Crockford touches briefly on this in JavaScript the Good Parts google tech talk video. Worth spending an hour to watch.


Checks that the type as well as the values match. This is important since (0 == false) is true but (0 === false) is not true.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜