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


i'm using jslint go through javascript, , it's returning many suggestions replace == (two equals signs) === (three equals signs) when doing things comparing idsele_unvehtype.value.length == 0 inside of if statement.

is there performance benefit replacing == ===?

any performance improvement welcomed many comparison operators exist.

if no type conversion takes place, there performance gain on ==?

the identity (===) operator behaves identically equality (==) operator except no type conversion done, , types must same considered equal.

reference: javascript tutorial: comparison operators

the == operator compare equality after doing necessary type conversions. === operator not conversion, if 2 values not same type === return false. both equally quick.

to quote douglas crockford's excellent javascript: parts,

javascript has 2 sets of equality operators: === , !==, , evil twins == , !=. ones work way expect. if 2 operands of same type , have same value, === produces true , !== produces false. evil twins right thing when operands of same type, if of different types, attempt coerce values. rules complicated , unmemorable. these of interesting cases:

'' == '0'           // false 0 == ''             // true 0 == '0'            // true  false == 'false'    // false false == '0'        // true  false == undefined  // false false == null       // false null == undefined   // true  ' \t\r\n ' == 0     // true 

the lack of transitivity alarming. advice never use evil twins. instead, use === , !==. of comparisons shown produce false === operator.


update:

a point brought @casebash in comments , in @phillipe laybaert's answer concerning reference types. reference types == , === act consistently 1 (except in special case).

var = [1,2,3]; var b = [1,2,3];  var c = { x: 1, y: 2 }; var d = { x: 1, y: 2 };  var e = "text"; var f = "te" + "xt";  == b            // false === b           // false  c == d            // false c === d           // false  e == f            // true e === f           // true 

the special case when compare literal object evaluates same literal, due tostring or valueof method. example, consider comparison of string literal string object created string constructor.

"abc" == new string("abc")    // true "abc" === new string("abc")   // false 

here == operator checking values of 2 objects , returning true, === seeing they're not same type , returning false. 1 correct? depends on you're trying compare. advice bypass question entirely , don't use string constructor create string objects.

reference
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -