[javascript] 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 ==?

The answer is


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.

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

Javascript strict equality

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

Javascript non equality


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

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

and

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

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.


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.


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 + "]")
    };
}

If you are making a web application or a secured page you should always use (only when possible)

===

because it will will check if it is the same content and if it is the same type!

so when someone enters:

var check = 1;
if(check == '1') {
    //someone continued with a string instead of number, most of the time useless for your webapp, most of the time entered by a user who does not now what he is doing (this will sometimes let your app crash), or even worse it is a hacker searching for weaknesses in your webapp!
}

but with

var check = 1;
if(check === 1) {
    //some continued with a number (no string) for your script
} else {
    alert('please enter a real number');
}

a hacker will never get deeper in the system to find bugs and hack your app or your users

my point it is that the

===

will add more security to your scripts

of course you can also check if the entered number is valid, is a string, etc.. with other if statements inside the first example, but this is for at least me more easier to understand and use

The reason I posted this is that the word 'more secure' or 'security' has never been said in this conversation (if you look at iCloud.com it uses 2019 times === and 1308 times ==, this also means that you sometimes have the use == instead of === because it will otherwise block your function, but as said in the begin you should use === as much as possible)


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)


In a typical script there will be no performance difference. More important may be the fact that thousand "===" is 1 KB heavier than thousand "==" :) JavaScript profilers can tell you if there is a performance difference in your case.

But personally I would do what JSLint suggests. This recommendation is there not because of performance issues, but because type coercion means ('\t\r\n' == 0) is true.


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


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".


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.


Use === if you want to compare 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, if you using ==, you basically 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);

In PHP and JavaScript, it is a strict equality operator. Which means, it will compare both type and values.


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

There is unlikely to be any performance difference between the two operations in your usage. There is no type-conversion to be done because both parameters are already the same type. Both operations will have a type comparison followed by a value comparison.


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.


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)


From the core javascript reference

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


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

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

The === operator is called a strict comparison operator, it does differ from the == operator.

Lets take 2 vars a and b.

For "a == b" to evaluate to true a and b need to be the same value.

In the case of "a === b" a and b must be the same value and also the same type for it to evaluate to true.

Take the following example

var a = 1;
var b = "1";

if (a == b) //evaluates to true as a and b are both 1
{
    alert("a == b");
}

if (a === b) //evaluates to false as a is not the same type as b
{
    alert("a === b");
}

In summary; using the == operator might evaluate to true in situations where you do not want it to so using the === operator would be safer.

In the 90% usage scenario it won't matter which one you use, but it is handy to know the difference when you get some unexpected behaviour one day.


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

Javascript strict equality

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

Javascript non equality


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

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

and

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

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.


Equality comparison:

Operator ==

Returns true, when both operands are equal. The operands are converted to the same type before being compared.

>>> 1 == 1
true
>>> 1 == 2
false
>>> 1 == '1'
true

Equality and type comparison:

Operator ===

Returns true if both operands are equal and of the same type. It's generally better and safer if you compare this way, because there's no behind-the-scenes type conversions.

>>> 1 === '1'
false
>>> 1 === 1
true

*Operators === vs == *

1 == true    =>    true
true == true    =>    true
1 === true    =>    false
true === true    =>    true

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.

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.


Here is a handy comparison table that shows the conversions that happen and the differences between == and ===.

As the conclusion states:

"Use three equals unless you fully understand the conversions that take place for two-equals."

http://dorey.github.io/JavaScript-Equality-Table/


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

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


In the answers here, I didn't read anything about what equal means. Some will say that === means equal and of the same type, but that's not really true. It actually means that both operands reference the same object, or in case of value types, have the same value.

So, let's take the following code:

var a = [1,2,3];
var b = [1,2,3];
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

The same here:

var a = { x: 1, y: 2 };
var b = { x: 1, y: 2 };
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

Or even:

var a = { };
var b = { };
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

This behavior is not always obvious. There's more to the story than being equal and being of the same type.

The rule is:

For value types (numbers):
a === b returns true if a and b have the same value and are of the same type

For reference types:
a === b returns true if a and b reference the exact same object

For strings:
a === b returns true if a and b are both strings and contain the exact same characters


Strings: the special case...

Strings are not value types, but in Javascript they behave like value types, so they will be "equal" when the characters in the string are the same and when they are of the same length (as explained in the third rule)

Now it becomes interesting:

var a = "12" + "3";
var b = "123";

alert(a === b); // returns true, because strings behave like value types

But how about this?:

var a = new String("123");
var b = "123";

alert(a === b); // returns false !! (but they are equal and of the same type)

I thought strings behave like value types? Well, it depends who you ask... In this case a and b are not the same type. a is of type Object, while b is of type string. Just remember that creating a string object using the String constructor creates something of type Object that behaves as a string most of the time.


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.


The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...

var x = 0;
var isTrue = x == null;
var isFalse = x === null;

Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...

CString x;
delete x;

Which obviously during runtime does very undefined things...

Google for implicit conversions in C++ and STL to get some of the arguments against it...


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".


Use === if you want to compare 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, if you using ==, you basically 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);

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.

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.


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

var a = new String("123");
var b = "123";

alert(a === b); // returns false !! (but they are equal and of the same type)

Saw this in one of the answers. a and b are not really the same type in this case, if you will check typeof(a) you will get 'object' and typeof(b) is 'string'.


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.


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.


=== cares if the objects are the same. Therefore, new String("Hello world") === "Hello world" returns false. However, == does not care about if the objects are the same; it just simply converts one argument into the other's type: if conversion is not possible, return false. Then new String("Hello world") == "Hello world" returns true instead of false.


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

Many times an untyped check would be handy because you do not care if the value is either undefined, null, 0 or ""


An interesting pictorial representation of the equality comparison between == and ===.

Source: http://dorey.github.io/JavaScript-Equality-Table/


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

Moral of the story:

Use === unless you fully understand the conversions that take place with ==.


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.


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.


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 

The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...

var x = 0;
var isTrue = x == null;
var isFalse = x === null;

Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...

CString x;
delete x;

Which obviously during runtime does very undefined things...

Google for implicit conversions in C++ and STL to get some of the arguments against it...


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

The equal comparison operator == is confusing and should be avoided.

If you HAVE TO live with it, then remember the following 3 things:

  1. It is not transitive: (a == b) and (b == c) does not lead to (a == c)
  2. It's mutually exclusive to its negation: (a == b) and (a != b) always hold opposite Boolean values, with all a and b.
  3. In case of doubt, learn by heart the following truth table:

EQUAL OPERATOR TRUTH TABLE IN JAVASCRIPT

  • Each row in the table is a set of 3 mutually "equal" values, meaning that any 2 values among them are equal using the equal == sign*

** STRANGE: note that any two values on the first column are not equal in that sense.**

''       == 0 == false   // Any two values among these 3 ones are equal with the == operator
'0'      == 0 == false   // Also a set of 3 equal values, note that only 0 and false are repeated
'\t'     == 0 == false   // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\r'     == 0 == false   // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\n'     == 0 == false   // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\t\r\n' == 0 == false   // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

null == undefined  // These two "default" values are not-equal to any of the listed values above
NaN                // NaN is not equal to any thing, even to itself.

1 == "1"    =>    true(define)
true === "true"    => false(undefined compare the type of variable)
Case 1
if(true === "true"){
  echo 'true'
}else{
 echo 'false undefined'
}
Ans :- false undefined because case 1 is check data type also with ===  
Case 2
if(1 == "1"){
  echo 'true define'
}else{
 echo 'false undefined'
}
Ans :- true define undefined because case 2 is not check data type with ==

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.


In a typical script there will be no performance difference. More important may be the fact that thousand "===" is 1 KB heavier than thousand "==" :) JavaScript profilers can tell you if there is a performance difference in your case.

But personally I would do what JSLint suggests. This recommendation is there not because of performance issues, but because type coercion means ('\t\r\n' == 0) is true.


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

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

and

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

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.


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, and is therefore faster (as according to This JS benchmark test) as it skips one step.


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;

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


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.


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


The === operator is called a strict comparison operator, it does differ from the == operator.

Lets take 2 vars a and b.

For "a == b" to evaluate to true a and b need to be the same value.

In the case of "a === b" a and b must be the same value and also the same type for it to evaluate to true.

Take the following example

var a = 1;
var b = "1";

if (a == b) //evaluates to true as a and b are both 1
{
    alert("a == b");
}

if (a === b) //evaluates to false as a is not the same type as b
{
    alert("a === b");
}

In summary; using the == operator might evaluate to true in situations where you do not want it to so using the === operator would be safer.

In the 90% usage scenario it won't matter which one you use, but it is handy to know the difference when you get some unexpected behaviour one day.


From the core javascript reference

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


null and undefined are nothingness, that is,

var a;
var b = null;

Here a and b do not have values. Whereas, 0, false and '' are all values. One thing common beween all these are that they are all falsy values, which means they all satisfy falsy conditions.

So, the 0, false and '' together form a sub-group. And on other hand, null & undefined form the second sub-group. Check the comparisons in the below image. null and undefined would equal. The other three would equal to each other. But, they all are treated as falsy conditions in JavaScript.

Enter image description here

This is same as any object (like {}, arrays, etc.), non-empty string & Boolean true are all truthy conditions. But, they are all not equal.


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

<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.


Simply

== means comparison between operands with type conversion

&

=== means comparison between operands without type conversion

Type conversion in javaScript means javaScript automatically convert any other data types to string data types.

For example:

123=='123'   //will return true, because JS convert integer 123 to string '123'
             //as we used '==' operator 

123==='123' //will return false, because JS do not convert integer 123 to string 
            //'123' as we used '===' operator 

The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...

var x = 0;
var isTrue = x == null;
var isFalse = x === null;

Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...

CString x;
delete x;

Which obviously during runtime does very undefined things...

Google for implicit conversions in C++ and STL to get some of the arguments against it...


The === operator is called a strict comparison operator, it does differ from the == operator.

Lets take 2 vars a and b.

For "a == b" to evaluate to true a and b need to be the same value.

In the case of "a === b" a and b must be the same value and also the same type for it to evaluate to true.

Take the following example

var a = 1;
var b = "1";

if (a == b) //evaluates to true as a and b are both 1
{
    alert("a == b");
}

if (a === b) //evaluates to false as a is not the same type as b
{
    alert("a === b");
}

In summary; using the == operator might evaluate to true in situations where you do not want it to so using the === operator would be safer.

In the 90% usage scenario it won't matter which one you use, but it is handy to know the difference when you get some unexpected behaviour one day.


The === operator is called a strict comparison operator, it does differ from the == operator.

Lets take 2 vars a and b.

For "a == b" to evaluate to true a and b need to be the same value.

In the case of "a === b" a and b must be the same value and also the same type for it to evaluate to true.

Take the following example

var a = 1;
var b = "1";

if (a == b) //evaluates to true as a and b are both 1
{
    alert("a == b");
}

if (a === b) //evaluates to false as a is not the same type as b
{
    alert("a === b");
}

In summary; using the == operator might evaluate to true in situations where you do not want it to so using the === operator would be safer.

In the 90% usage scenario it won't matter which one you use, but it is handy to know the difference when you get some unexpected behaviour one day.


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, and is therefore faster (as according to This JS benchmark test) as it skips one step.


1 == "1"    =>    true(define)
true === "true"    => false(undefined compare the type of variable)
Case 1
if(true === "true"){
  echo 'true'
}else{
 echo 'false undefined'
}
Ans :- false undefined because case 1 is check data type also with ===  
Case 2
if(1 == "1"){
  echo 'true define'
}else{
 echo 'false undefined'
}
Ans :- true define undefined because case 2 is not check data type with ==

In a typical script there will be no performance difference. More important may be the fact that thousand "===" is 1 KB heavier than thousand "==" :) JavaScript profilers can tell you if there is a performance difference in your case.

But personally I would do what JSLint suggests. This recommendation is there not because of performance issues, but because type coercion means ('\t\r\n' == 0) is true.


The equal comparison operator == is confusing and should be avoided.

If you HAVE TO live with it, then remember the following 3 things:

  1. It is not transitive: (a == b) and (b == c) does not lead to (a == c)
  2. It's mutually exclusive to its negation: (a == b) and (a != b) always hold opposite Boolean values, with all a and b.
  3. In case of doubt, learn by heart the following truth table:

EQUAL OPERATOR TRUTH TABLE IN JAVASCRIPT

  • Each row in the table is a set of 3 mutually "equal" values, meaning that any 2 values among them are equal using the equal == sign*

** STRANGE: note that any two values on the first column are not equal in that sense.**

''       == 0 == false   // Any two values among these 3 ones are equal with the == operator
'0'      == 0 == false   // Also a set of 3 equal values, note that only 0 and false are repeated
'\t'     == 0 == false   // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\r'     == 0 == false   // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\n'     == 0 == false   // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\t\r\n' == 0 == false   // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

null == undefined  // These two "default" values are not-equal to any of the listed values above
NaN                // NaN is not equal to any thing, even to itself.

Here is a handy comparison table that shows the conversions that happen and the differences between == and ===.

As the conclusion states:

"Use three equals unless you fully understand the conversions that take place for two-equals."

http://dorey.github.io/JavaScript-Equality-Table/


In PHP and JavaScript, it is a strict equality operator. Which means, it will compare both type and values.


If you are making a web application or a secured page you should always use (only when possible)

===

because it will will check if it is the same content and if it is the same type!

so when someone enters:

var check = 1;
if(check == '1') {
    //someone continued with a string instead of number, most of the time useless for your webapp, most of the time entered by a user who does not now what he is doing (this will sometimes let your app crash), or even worse it is a hacker searching for weaknesses in your webapp!
}

but with

var check = 1;
if(check === 1) {
    //some continued with a number (no string) for your script
} else {
    alert('please enter a real number');
}

a hacker will never get deeper in the system to find bugs and hack your app or your users

my point it is that the

===

will add more security to your scripts

of course you can also check if the entered number is valid, is a string, etc.. with other if statements inside the first example, but this is for at least me more easier to understand and use

The reason I posted this is that the word 'more secure' or 'security' has never been said in this conversation (if you look at iCloud.com it uses 2019 times === and 1308 times ==, this also means that you sometimes have the use == instead of === because it will otherwise block your function, but as said in the begin you should use === as much as possible)


In JavaScript it means of the same value and type.

For example,

4 == "4" // will return true

but

4 === "4" // will return false 

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

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


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.

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


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.


var a = new String("123");
var b = "123";

alert(a === b); // returns false !! (but they are equal and of the same type)

Saw this in one of the answers. a and b are not really the same type in this case, if you will check typeof(a) you will get 'object' and typeof(b) is 'string'.


There is unlikely to be any performance difference between the two operations in your usage. There is no type-conversion to be done because both parameters are already the same type. Both operations will have a type comparison followed by a value comparison.


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

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

and

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

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.


In JavaScript it means of the same value and type.

For example,

4 == "4" // will return true

but

4 === "4" // will return false 

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

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.


=== cares if the objects are the same. Therefore, new String("Hello world") === "Hello world" returns false. However, == does not care about if the objects are the same; it just simply converts one argument into the other's type: if conversion is not possible, return false. Then new String("Hello world") == "Hello world" returns true instead of false.


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

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;

Equality comparison:

Operator ==

Returns true, when both operands are equal. The operands are converted to the same type before being compared.

>>> 1 == 1
true
>>> 1 == 2
false
>>> 1 == '1'
true

Equality and type comparison:

Operator ===

Returns true if both operands are equal and of the same type. It's generally better and safer if you compare this way, because there's no behind-the-scenes type conversions.

>>> 1 === '1'
false
>>> 1 === 1
true

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.


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

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.


Simply

== means comparison between operands with type conversion

&

=== means comparison between operands without type conversion

Type conversion in javaScript means javaScript automatically convert any other data types to string data types.

For example:

123=='123'   //will return true, because JS convert integer 123 to string '123'
             //as we used '==' operator 

123==='123' //will return false, because JS do not convert integer 123 to string 
            //'123' as we used '===' operator 

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.


An interesting pictorial representation of the equality comparison between == and ===.

Source: http://dorey.github.io/JavaScript-Equality-Table/


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

Moral of the story:

Use === unless you fully understand the conversions that take place with ==.


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

Many times an untyped check would be handy because you do not care if the value is either undefined, null, 0 or ""


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, and is therefore faster (as according to This JS benchmark test) as it skips one step.


There is unlikely to be any performance difference between the two operations in your usage. There is no type-conversion to be done because both parameters are already the same type. Both operations will have a type comparison followed by a value comparison.


In the answers here, I didn't read anything about what equal means. Some will say that === means equal and of the same type, but that's not really true. It actually means that both operands reference the same object, or in case of value types, have the same value.

So, let's take the following code:

var a = [1,2,3];
var b = [1,2,3];
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

The same here:

var a = { x: 1, y: 2 };
var b = { x: 1, y: 2 };
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

Or even:

var a = { };
var b = { };
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

This behavior is not always obvious. There's more to the story than being equal and being of the same type.

The rule is:

For value types (numbers):
a === b returns true if a and b have the same value and are of the same type

For reference types:
a === b returns true if a and b reference the exact same object

For strings:
a === b returns true if a and b are both strings and contain the exact same characters


Strings: the special case...

Strings are not value types, but in Javascript they behave like value types, so they will be "equal" when the characters in the string are the same and when they are of the same length (as explained in the third rule)

Now it becomes interesting:

var a = "12" + "3";
var b = "123";

alert(a === b); // returns true, because strings behave like value types

But how about this?:

var a = new String("123");
var b = "123";

alert(a === b); // returns false !! (but they are equal and of the same type)

I thought strings behave like value types? Well, it depends who you ask... In this case a and b are not the same type. a is of type Object, while b is of type string. Just remember that creating a string object using the String constructor creates something of type Object that behaves as a string most of the time.


There is unlikely to be any performance difference between the two operations in your usage. There is no type-conversion to be done because both parameters are already the same type. Both operations will have a type comparison followed by a value comparison.


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.


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, and is therefore faster (as according to This JS benchmark test) as it skips one step.


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

<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.


In a typical script there will be no performance difference. More important may be the fact that thousand "===" is 1 KB heavier than thousand "==" :) JavaScript profilers can tell you if there is a performance difference in your case.

But personally I would do what JSLint suggests. This recommendation is there not because of performance issues, but because type coercion means ('\t\r\n' == 0) is true.


*Operators === vs == *

1 == true    =>    true
true == true    =>    true
1 === true    =>    false
true === true    =>    true

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 + "]")
    };
}

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 

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to operators

What is the difference between i = i + 1 and i += 1 in a 'for' loop? Using OR operator in a jquery if statement What is <=> (the 'Spaceship' Operator) in PHP 7? What does question mark and dot operator ?. mean in C# 6.0? Boolean operators ( &&, -a, ||, -o ) in Bash PowerShell and the -contains operator How do I print the percent sign(%) in c Using the && operator in an if statement What do these operators mean (** , ^ , %, //)? How to check if div element is empty

Examples related to equality

Python if not == vs if != Comparing arrays for equality in C++ Correct way to override Equals() and GetHashCode() Determine if 2 lists have the same elements, regardless of order? equals vs Arrays.equals in Java What is the difference between == and equals() in Java? What's the difference between equal?, eql?, ===, and ==? bash string equality jQuery object equality String comparison in Python: is vs. ==

Examples related to equality-operator

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

Examples related to identity-operator

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