Which equals operator (== vs ===) should be used i

2020-01-22 10:31发布

I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace == (two equals signs) with === (three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement.

Is there a performance benefit to replacing == with ===?

Any performance improvement would be welcomed as many comparison operators exist.

If no type conversion takes place, would there be a performance gain over ==?

30条回答
我想做一个坏孩纸
2楼-- · 2020-01-22 10:34

It's a strict check test.

It's a good thing especially if you're checking between 0 and false and null.

For example, if you have:

$a = 0;

Then:

$a==0; 
$a==NULL;
$a==false;

All returns true and you may not want this. Let's suppose you have a function that can return the 0th index of an array or false on failure. If you check with "==" false, you can get a confusing result.

So with the same thing as above, but a strict test:

$a = 0;

$a===0; // returns true
$a===NULL; // returns false
$a===false; // returns false
查看更多
不美不萌又怎样
3楼-- · 2020-01-22 10:37

JavaScript === vs == .

0==false   // true
0===false  // false, because they are of a different type
1=="1"     // true, auto type coercion
1==="1"    // false, because they are of a different type
查看更多
劫难
4楼-- · 2020-01-22 10:37

A simple example is

2 == '2'  -> true, values are SAME because of type conversion.

2 === '2'  -> false, values are NOT SAME because of no type conversion.
查看更多
闹够了就滚
5楼-- · 2020-01-22 10:37

*Operators === vs == *

1 == true    =>    true
true == true    =>    true
1 === true    =>    false
true === true    =>    true
查看更多
该账号已被封号
6楼-- · 2020-01-22 10:38

It checks if same sides are equal in type as well as value.

Example:

'1' === 1 // will return "false" because `string` is not a `number`

Common example:

0 == ''  // will be "true", but it's very common to want this check to be "false"

Another common example:

null == undefined // returns "true", but in most cases a distinction is necessary
查看更多
我命由我不由天
7楼-- · 2020-01-22 10:38

The top 2 answers both mentioned == means equality and === means identity. Unfortunately, this statement is incorrect.

If both operands of == are objects, then they are compared to see if they are the same object. If both operands point to the same object, then the equal operator returns true. Otherwise, the two are not equal.

var a = [1, 2, 3];  
var b = [1, 2, 3];  
console.log(a == b)  // false  
console.log(a === b) // false  

In the code above, both == and === get false because a and b are not the same objects.

That's to say: if both operands of == are objects, == behaves same as ===, which also means identity. The essential difference of this two operators is about type conversion. == has conversion before it checks equality, but === does not.

查看更多
登录 后发表回答