bcasp
bcasp

Reputation: 57357

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

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 ==?

Upvotes: 5645

Views: 2189270

Answers (30)

Aniket Thakur
Aniket Thakur

Reputation: 68985

Yes! It does matter.

=== operator in javascript checks value as well as type where as == operator just checks the value (does type conversion if required).

enter image description here

You can easily test it. Paste following code in an HTML file and open it in browser

<head>

<script>

function onPageLoad()
{
    var x = "5";
    var y = 5;
    alert(x === 5);
};

</script>

</head>

<body onload='onPageLoad();'>

You will get 'false' in alert. Now modify the onPageLoad() method to alert(x == 5); you will get true.

Upvotes: 43

Alireza
Alireza

Reputation: 104870

Use === if you want to compare a couple of things in JavaScript, it's called strict equality, it means this will return true if only both type and value are the same, so there wouldn't be any unwanted type correction for you and if you using ==, you don't care about the type and in many cases, you could face issues with loose equality comparison.

Strict equality using ===

Strict equality compares two values for equality. Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal. Otherwise, if the values have the same type and are not numbers, they're considered equal if they have the same value. Finally, if both values are numbers, they're considered equal if they're both not NaN and are the same value, or if one is +0 and one is -0.

var num = 0;
var obj = new String('0');
var str = '0';

console.log(num === num); // true
console.log(obj === obj); // true
console.log(str === str); // true

console.log(num === obj); // false
console.log(num === str); // false
console.log(obj === str); // false
console.log(null === undefined); // false
console.log(obj === null); // false
console.log(obj === undefined); // false


Loose equality using ==

Loose equality compares two values for equality, after converting both values to a common type. After conversions (one or both sides may undergo conversions), the final equality comparison is performed exactly as === performs it. Loose equality is symmetric: A == B always has identical semantics to B == A for any values of A and B (except for the order of applied conversions).

var num = 0;
var obj = new String('0');
var str = '0';

console.log(num == num); // true
console.log(obj == obj); // true
console.log(str == str); // true

console.log(num == obj); // true
console.log(num == str); // true
console.log(obj == str); // true
console.log(null == undefined); // true

// both false, except in rare cases
console.log(obj == null);
console.log(obj == undefined);

Upvotes: 0

vsync
vsync

Reputation: 130570

=== checks 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

From my long-time experience an untyped check is preferable because you do not care if the value is either undefined, null, 0 or ""

Another comparison approach is using Object.is and here's a great informative answer about it.

Upvotes: 90

Bill the Lizard
Bill the Lizard

Reputation: 405995

The strict equality operator (===) behaves identically to the abstract equality operator (==) except no type conversion is done, and the types must be the same to be considered equal.

Reference: JavaScript Tutorial: Comparison Operators

The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. Both are equally quick.

To quote Douglas Crockford's excellent JavaScript: The Good Parts,

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. The rules by which they do that are complicated and unmemorable. These are some of the 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

Equality Comparison Table

The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.


Update

A good point was brought up by @Casebash in the comments and in @Phillipe Laybaert's answer concerning objects. For objects, == and === act consistently with one another (except in a special case).

var a = [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";

a == b            // false
a === b           // false

c == d            // false
c === d           // false

e == f            // true
e === f           // true

The special case is when you compare a primitive with an object that evaluates to the same primitive, due to its toString or valueOf method. For example, consider the comparison of a string primitive with a string object created using the String constructor.

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

Here the == operator is checking the values of the two objects and returning true, but the === is seeing that they're not the same type and returning false. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the String constructor to create string objects from string literals.

Reference
https://262.ecma-international.org/5.1/#sec-11.9.3

Upvotes: 7207

Andreas Grech
Andreas Grech

Reputation: 108000

Using the == operator (Equality)

true == 1; //true, because 'true' is converted to 1 and then compared
"2" == 2;  //true, because "2" is converted to 2 and then compared

Using the === operator (Identity)

true === 1; //false
"2" === 2;  //false

This is because the equality operator == does type coercion, meaning that the interpreter implicitly tries to convert the values before comparing.

On the other hand, the identity operator === does not do type coercion, and thus does not convert the values when comparing.

Upvotes: 1256

SNag
SNag

Reputation: 18151

Here's an interesting visualisation of the equality comparison between == and ===.

Source: https://github.com/dorey/JavaScript-Equality-Table (demo, unified demo)


var1 === var2

When using === for JavaScript equality testing, everything is as is.
Nothing gets converted before being evaluated.

Equality evaluation of === in JS

var1 == var2

When using == for JavaScript equality testing, some funky conversions take place.

Equality evaluation of == in JS

Summary of equality in Javascript

Equality in Javascript


Conclusion:

Always use ===, unless you fully understand the funky conversions that take place with ==.

Upvotes: 902

mar10
mar10

Reputation: 14814

As a rule of thumb, I would generally use === instead of == (and !== instead of !=).

Reasons are explained in in the answers above and also Douglas Crockford is pretty clear about it (JavaScript: The Good Parts).

However there is one single exception: == null is an efficient way to check for 'is null or undefined':

if( value == null ){
    // value is either null or undefined
}

For example jQuery 1.9.1 uses this pattern 43 times, and the JSHint syntax checker even provides the eqnull relaxing option for this reason.

From the jQuery style guide:

Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by way of null.

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

EDIT 2021-03:

Nowadays most browsers support the Nullish coalescing operator (??) and the Logical nullish assignment (??=), which allows a more concise way to assign a default value if a variable is null or undefined, for example:

if (a.speed == null) {
  // Set default if null or undefined
  a.speed = 42;
}

can be written as any of these forms

a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;

Upvotes: 39

Amit
Amit

Reputation: 847

Simply

== means comparison between operands with type coercion

and

=== means comparison between operands without type coercion.

Type coercion in JavaScript means automatically converting data types to other data types.

For example:

123 == "123"  // Returns true, because JS coerces string "123" to number 123
              // and then goes on to compare `123 == 123`.

123 === "123" // Returns false, because JS does not coerce values of different types here.

Upvotes: 41

Simon Scarfe
Simon Scarfe

Reputation: 9638

I tested this in Firefox with Firebug using code like this:

console.time("testEquality");
var n = 0;
while (true) {
  n++;
  if (n == 100000)
    break;
}
console.timeEnd("testEquality");

and

console.time("testTypeEquality");
var n = 0;
while (true) {
  n++;
  if (n === 100000)
    break;
}
console.timeEnd("testTypeEquality");

My results (tested five times each and averaged):

==: 115.2
===: 114.4

So I'd say that the miniscule difference (this is over 100000 iterations, remember) is negligible. Performance isn't a reason to do ===. Type safety (well, as safe as you're going to get in JavaScript), and code quality is.

Upvotes: 113

Sharad Kale
Sharad Kale

Reputation: 971

== operator just compares the values not datatype.

=== operator compare the values with comparison of its datatype.

eg :

1 == "1" //true

1 === "1" //false

This operator ("===") used in languages which performs automatic type cast eg. PHP, Javascript.
"===" operator helps to prevent unexpected comparison caused by automatic typecast.

Upvotes: 11

CodeFarmer
CodeFarmer

Reputation: 2706

My reasoning process using emacs org-mode and node.js to run a test.

| use ==     | '' | '0' | false | 'false' | undefined | null | ' \t\r\n ' |
| ''         | x  | f   | t     | f       | f         | f    | f          |
| '0'        |    | x   | t     | f       | f         | f    | f          |
| false      |    |     | x     | f       | f         | f    | t          |
| 'false'    |    |     |       | x       | f         | f    | f          |
| undefined  |    |     |       |         | x         | t    | f          |
| null       |    |     |       |         |           | x    | f          |
| ' \t\r\n ' |    |     |       |         |           |      | x          | 



| use ===    | '' | '0' | false | 'false' | undefined | null | ' \t\r\n ' |
| ''         | x  | f   | f     | f       | f         | f    | f          |
| '0'        |    | x   | f     | f       | f         | f    | f          |
| false      |    |     | x     | f       | f         | f    | f          |
| 'false'    |    |     |       | x       | f         | f    | f          |
| undefined  |    |     |       |         | x         | f    | f          |
| null       |    |     |       |         |           | x    | f          |
| ' \t\r\n ' |    |     |       |         |           |      | x          |

My test script below: run > node xxx.js

var rowItems = ['', '0', false, 'false', undefined, null, ' \t\r\n ']
var colItems = rowItems

for(var i = 0; i < rowItems.length; i++) {
    for (var j = 0; j < colItems.length; j++) {
        var r = (rowItems[i] === colItems[j]) ? true : false;
        console.log(rowItems[i] + " = " + colItems[j] + " " + r + " [" + i + "] ==> [" + j + "]")
    };
}

Upvotes: 13

Luis Perez
Luis Perez

Reputation: 28130

Why == is so unpredictable?

What do you get when you compare an empty string "" with the number zero 0?

true

Yep, that's right according to == an empty string and the number zero are the same time.

And it doesn't end there, here's another one:

'0' == false // true

Things get really weird with arrays.

[1] == true // true
[] == false // true
[[]] == false // true
[0] == false // true

Then weirder with strings

[1,2,3] == '1,2,3' // true - REALLY?!
'\r\n\t' == 0 // true - Come on!

It get's worse:

When is equal not equal?

let A = ''  // empty string
let B = 0   // zero
let C = '0' // zero string

A == B // true - ok... 
B == C // true - so far so good...
A == C // **FALSE** - Plot twist!

Let me say that again:

(A == B) && (B == C) // true
(A == C) // **FALSE**

And this is just the crazy stuff you get with primitives.

It's a whole new level of crazy when you use == with objects.

At this point your probably wondering...

Why does this happen?

Well it's because unlike "triple equals" (===) which just checks if two values are the same.

== does a whole bunch of other stuff.

It has special handling for functions, special handling for nulls, undefined, strings, you name it.

It get's pretty wacky.

In fact, if you tried to write a function that does what == does it would look something like this:

function isEqual(x, y) { // if `==` were a function
    if(typeof y === typeof x) return y === x;
    // treat null and undefined the same
    var xIsNothing = (y === undefined) || (y === null);
    var yIsNothing = (x === undefined) || (x === null);

    if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);

    if(typeof y === "function" || typeof x === "function") {
        // if either value is a string 
        // convert the function into a string and compare
        if(typeof x === "string") {
            return x === y.toString();
        } else if(typeof y === "string") {
            return x.toString() === y;
        } 
        return false;
    }

    if(typeof x === "object") x = toPrimitive(x);
    if(typeof y === "object") y = toPrimitive(y);
    if(typeof y === typeof x) return y === x;

    // convert x and y into numbers if they are not already use the "+" trick
    if(typeof x !== "number") x = +x;
    if(typeof y !== "number") y = +y;
    // actually the real `==` is even more complicated than this, especially in ES6
    return x === y;
}

function toPrimitive(obj) {
    var value = obj.valueOf();
    if(obj !== value) return value;
    return obj.toString();
}

So what does this mean?

It means == is complicated.

Because it's complicated it's hard to know what's going to happen when you use it.

Which means you could end up with bugs.

So the moral of the story is...

Make your life less complicated.

Use === instead of ==.

The End.

Upvotes: 101

Bekim Bacaj
Bekim Bacaj

Reputation: 5955

The dilemma of "Should I use == or === in JavaScript comparison" is equal or analogous to a question of: "Should I use a 'spoon' or a 'fork' for eating.

The only reasonable answer to this question is that

  1. You should use Dynamic Type comparison e.g.:== for loose Type comparisons.
  2. You should use Static Type comparison e.g.:=== for strong Type comparisons.

That's because they are not the same. They don't have the same purpose and are not meant to be used for the same purpose.

Of course both 'forks' and 'spoons' are meant for 'eating', but you will chose to use them accordingly to what you've been served to eat.

Meaning: you'll resolve to using a 'spoon' i.e.: == for having a 'soup', and / or the 'fork' i.e.: === for picking.

Asking if it is better to use a "fork" or a "spoon" for "eating" - is equall to asking if it is better to use a static [===] versus dynamic [==] eq., op. in JS. Both questions are equally wrong and reflect a very narrow or shallow understanding of the subject in question.

Upvotes: 0

garakchy
garakchy

Reputation: 584

JavaScript has both strict and type–converting comparisons. A strict comparison (e.g., ===) is only true if the operands are of the same type. The more commonly used abstract comparison (e.g. ==) converts the operands to the same Type before making the comparison.

  • The equality (==) operator converts the operands if they are not of the same type, then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the string operand is converted to a number if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

    Syntax:

    x == y

    Examples:

    3 == 3     // true
    "3" == 3   // true
    3 == '3'   // true
    
  • The identity/strict equality(===) operator returns true if the operands are strictly equal (see above) with no type conversion.

    Syntax:

    x === y

    Examples:

    3 === 3 // true

For reference: Comparison operators (Mozilla Developer Network)

Upvotes: 18

ashes
ashes

Reputation: 641

JSLint sometimes gives you unrealistic reasons to modify stuff. === has exactly the same performance as == if the types are already the same.

It is faster only when the types are not the same, in which case it does not try to convert types but directly returns a false.

So, IMHO, JSLint maybe used to write new code, but useless over-optimizing should be avoided at all costs.

Meaning, there is no reason to change == to === in a check like if (a == 'test') when you know it for a fact that a can only be a String.

Modifying a lot of code that way wastes developers' and reviewers' time and achieves nothing.

Upvotes: 33

Niraj CHoubey
Niraj CHoubey

Reputation: 467

=== operator checks the values as well as the types of the variables for equality.

== operator just checks the value of the variables for equality.

Upvotes: 35

Neil Meyer
Neil Meyer

Reputation: 585

Strict equality is for the most part better

The fact that Javascript is a loosely typed language needs to be in the front of your mind constantly as you work with it. As long as the data structure is the same there really is no reason as to not use strict equality, with regular equality you often have an implicit conversion of values that happens automatically, this can have far-reaching effects on your code. It is very easy to have problems with this conversion seeing as they happen automatically.

With strict equality there is no automatic implicit conversion as the values must already be of the correct data structure.

Upvotes: 2

Narendra Kalekar
Narendra Kalekar

Reputation: 118

The reason it suggest to replace == with === is that the === operator is more reliable than ==. In our context reliable means === also goes for type checking. Considering the best programming practices we should always choose more reliable feature over less reliable one. Again whenever we think about exactly equal to operator most of the time, we are by default consider the type should be same. As === provides the same, we should go for it.

Upvotes: 0

Pop Catalin
Pop Catalin

Reputation: 62970

It means equality without type coercion type coercion means JavaScript do not automatically convert any other data types to string data types

0==false   // true,although they are different types

0===false  // false,as they are different types

2=='2'    //true,different types,one is string and another is integer but 
            javaScript convert 2 to string by using == operator 

2==='2'  //false because by using === operator ,javaScript do not convert 
           integer to string 

2===2   //true because both have same value and same types 

Upvotes: 56

Different's Between = , = = , = = =

  • = operator Used to just assign the value.
  • = = operator Used to just compares the values not datatype
  • = = = operator Used to Compare the values as well as datatype.

Upvotes: 7

Rotimi
Rotimi

Reputation: 4825

First, some terminology about Javascript string equals: Double equals is officially known as the abstract equality comparison operator while triple equals is termed the strict equality comparison operator. The difference between them can be summed up as follows: Abstract equality will attempt to resolve the data types via type coercion before making a comparison. Strict equality will return false if the types are different. Consider the following example:

console.log(3 == "3"); // true
console.log(3 === "3"); // false.
console.log(3 == "3"); // true
console.log(3 === "3"); // false.

Using two equal signs returns true because the string “3” is converted to the number 3 before the comparison is made. Three equal signs sees that the types are different and returns false. Here’s another:

console.log(true == '1'); // true
console.log(true === '1'); // false
console.log(true == '1'); // true
console.log(true === '1'); // false

Again, the abstract equality comparison performs a type conversion. In this case both the boolean true and the string ‘1’ are converted to the number 1 and the result is true. Strict equality returns false.

If you understand that you are well on your way to distinguishing between == and ===. However, there’s some scenarios where the behavior of these operators is non intuitive. Let’s take a look at some more examples:

console.log(undefined == null); // true
console.log(undefined === null); // false. Undefined and null are distinct types and are not interchangeable.
console.log(undefined == null); // true     
console.log(undefined === null); // false. Undefined and null are distinct types and are not interchangeable.

console.log(true == 'true'); // false. A string will not be converted to a boolean and vice versa.
console.log(true === 'true'); // false
console.log(true == 'true'); // false. A string will not be converted to a boolean and vice versa.
console.log(true === 'true'); // false

The example below is interesting because it illustrates that string literals are different from string objects.

console.log("This is a string." == new String("This is a string.")); // true
console.log("This is a string." === new String("This is a string.")); // false
console.log("This is a string." == new String("This is a string.")); // true
console.log("This is a string." === new String("This is a string.")); // false

Upvotes: 2

yanguya995
yanguya995

Reputation: 143

Javascript is loosely typed just like php is,

var x = "20";
var y =20;

if (x===y) // false

This will always give you a false because even though the values of the variables are the same, the data types are not

One is string the the other is int

If(x==y)//true

This however just checks if the content is the same, regardless of the data types...

I dont want to say the values are equal because a string value cannot be equal to an int value logically

Upvotes: 0

Oleksandr
Oleksandr

Reputation: 5668

always use '===' and you will avoid thousand of mistakes. nowadays using triple equality is more preferable by different style guides, because it compares taking into account type of operands.

Upvotes: 7

Alex Gray
Alex Gray

Reputation: 16473

One unmentioned reason to use === - is in the case that you are co-existing with / cross-compiling to/from coffee-script. From The Little Book on CoffeeScript...

The weak equality comparison in JavaScript has some confusing behavior and is often the source of confusing bugs.

The solution is to instead use the strict equality operator, which consists of three equal signs: ===. It works exactly like the normal equality operator, but without any type coercion. It's recommended to always use the strict equality operator, and explicitly convert types if needs be.

If you are regularly converting to and from coffee-script, you should just use ===. In fact, the coffee-script compiler will force you to...

CoffeeScript solves this by simply replacing all weak comparisons with strict ones, in other words converting all == comparators into ===. You can't do a a weak equality comparison in CoffeeScript, and you should explicitly convert types before comparing them if necessary.

Upvotes: 5

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19130

Yes, there is a big difference between equality == and identity === operators.
Usually the identity operator performs faster, because no types conversion is done. But if the values are of the same type, you'll see no difference.
Check my post The legend of JavaScript equality operator, which explains the details, including the types conversion & comparison algorithms, with a lot of examples.

Upvotes: 5

user2496033
user2496033

Reputation:

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

Upvotes: 58

Paul Butcher
Paul Butcher

Reputation: 6956

From the core javascript reference

=== Returns true if the operands are strictly equal (see above) with no type conversion.

Upvotes: 23

nalply
nalply

Reputation: 28777

Let me add this counsel:

If in doubt, read the specification!

ECMA-262 is the specification for a scripting language of which JavaScript is a dialect. Of course in practice it matters more how the most important browsers behave than an esoteric definition of how something is supposed to be handled. But it is helpful to understand why new String("a") !== "a".

Please let me explain how to read the specification to clarify this question. I see that in this very old topic nobody had an answer for the very strange effect. So, if you can read a specification, this will help you in your profession tremendously. It is an acquired skill. So, let's continue.

Searching the PDF file for === brings me to page 56 of the specification: 11.9.4. The Strict Equals Operator ( === ), and after wading through the specificationalese I find:

11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
  1. If Type(x) is different from Type(y), return false.
  2. If Type(x) is Undefined, return true.
  3. If Type(x) is Null, return true.
  4. If Type(x) is not Number, go to step 11.
  5. If x is NaN, return false.
  6. If y is NaN, return false.
  7. If x is the same number value as y, return true.
  8. If x is +0 and y is −0, return true.
  9. If x is −0 and y is +0, return true.
  10. Return false.
  11. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
  12. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
  13. Return true if x and y refer to the same object or if they refer to objects joined to each other (see 13.1.2). Otherwise, return false.

Interesting is step 11. Yes, strings are treated as value types. But this does not explain why new String("a") !== "a". Do we have a browser not conforming to ECMA-262?

Not so fast!

Let's check the types of the operands. Try it out for yourself by wrapping them in typeof(). I find that new String("a") is an object, and step 1 is used: return false if the types are different.

If you wonder why new String("a") does not return a string, how about some exercise reading a specification? Have fun!


Aidiakapi wrote this in a comment below:

From the specification

11.2.2 The new Operator:

If Type(constructor) is not Object, throw a TypeError exception.

With other words, if String wouldn't be of type Object it couldn't be used with the new operator.

new always returns an Object, even for String constructors, too. And alas! The value semantics for strings (see step 11) is lost.

And this finally means: new String("a") !== "a".

Upvotes: 287

Samar Panda
Samar Panda

Reputation: 4324

Javascript execution flow diagram for strict equality / Comparison '==='

Javascript strict equality

Javascript execution flow diagram for non strict equality / comparison '=='

Javascript non equality

Upvotes: 76

Akshay Khale
Akshay Khale

Reputation: 8371

The javascript is a weakly typed language i.e. without any data-types as there in C,c++ eg. int, boolean, float etc. thus a variable can hold any type of value, that why these special comparison operators are there

Eg

var i = 20;var j = "20";

if we apply comparison operators these variables result will be

i==j //result is true

or

j != i//result is false

for that we need a special comparison operators which checks for the value as well as for the data type of the variable

if we do

i===j //result is false

Upvotes: 11

Related Questions