开发者

when to use === operator check in JavaScript? [duplicate]

开发者 https://www.devze.com 2023-01-01 04:01 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Javascript === vs == : Does it matter which “equal” operator I use?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

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

As the 开发者_开发技巧title states; when should you use the === operator check when using JavaScript, and when not to.

Edit: more complete answer found here. Thanks to Mark Byers for pointing it out.

_L


It is strict type equality operator. It not only checks whether two are equal in value but also of the same type.

Consider a situation when you compare numbers or strings:

if (4 === 4) // same value and type
{
  // true
}

but

if (4 == "4") // same value and different type but == used
{
  // true
}

and

if (4 === "4") // same value but different type
{
  // false
}

This applies to objects as well as arrays.

So in above cases, you have to make sensible choice whether to use == or ===

It is good idea to use === when you are sure about the type as well


When you wish to inhibit implied typecasts. For example:

3 == '3'

is true, whereas this is not:

3 === '3'

Douglas Crockford recommends always using strict comparison.


You use it to check if a variable's containing value and type is same as the compared one.

0

精彩评论

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