5645

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

47 Answers 47

1
2
18

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)

17

*Operators === vs == *

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

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)

13

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

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

1
  • This answer is a bit misguided, or, at least, not very precise… “objects”? Do you mean “types”? == does care if the types are the same; it delegates to strict equality comparison if they are. Two objects are compared by reference, but that’s the case for both operators. “if conversion is not possible” — I guess… but coercion is usually possible, and that’s not sufficient to cause one or the other result of the comparison, e.g. "undefined" != undefined, even though coercion would be possible. Commented Mar 15, 2021 at 9:20
11

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
11

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

2
  • for '==' dataType is not important
    – mrmr68
    Commented May 25, 2017 at 12:04
  • @mrmr68 The type of the operands of the Abstract Equality Comparison is very important — it’s used to coerce the operands to other types so they can be compared. Commented May 22, 2020 at 20:13
7

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.

0
7

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

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.

5

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.

2

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
2

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.

0

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

0

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.

0

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.

5
  • p.s.: JSLint (or Crockford ) is wrong for insisting, or asking you to use strict type comparison when dealing with values of the same type. The JavaScript length property is always of type: number. And therefore no room or a possibility for fake positives. Furthermore, there is no need for dSele_UNVEHtype.value.length === 0 when you can use a direct shorthand of !dSele_UNVEHtype.value.length instead. Commented Dec 5, 2017 at 22:08
  • 4
    Why would you answer a 9 year old question, which already has 49 answers, which also has an accepted answer with over 5k upvotes, with an answer that contains a weird analogy and doesn't explain anything what has not been said already?
    – Jasper
    Commented Dec 22, 2017 at 13:49
  • 2
    Because there are to many professional misuses of JavaScript no matter how old they are. And you for instance was unable to understand what's it all about and capture the essence of the difference Live Script makes in contrast to static type languages. And why do we need its intelligent dynamics. JavaScript was made for creative intelligent people not for dorks. Commented Dec 26, 2017 at 13:13
  • 3
    Yes I agree there are many misuses of JavaScript. However I still think your analogy is weird as in it can be easily misunderstood, and it does not cover the core basics in a meaningful way.
    – Jasper
    Commented Dec 27, 2017 at 8:22
  • The analogy given is the best ever illustration of their difference and the quality of use case. This is the best short essay to learn the absolute essence even if you are a complete newcomer to JS. And is equally good, probably better than my late answer on how to empty a JS array [for real]. Commented Dec 28, 2017 at 17:14
0

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);
2
  • I do believe it's subjective in regards to what you should/should not do, and misleading to tell someone to always use a particular action. While I agree than in most cases we care to use '===' vs. '==', there may be a particular case where you want the type conversion done. - Cannot think of an exact use case off the top of my head, but perhaps the design is to have a loose check. Regardless, if something is included in the language, it's there for a reason. We should try to avoid blanketing statements of 'always do x' in my opinion.
    – sramzan
    Commented May 18, 2017 at 15:45
  • I knid of agree with you, if you read my whole answer, you see I explain in more details later on, to be honest there are not many cases we use and need loose comparation in Javascript... I can say less than 5 percent, even much less, but I use ´always´ for those people with no js background, which think == check strict comparation in JavaScript, they learn to be catious and not using it at first place, but as they get more expert, they know in which rare cases they might use it. That's why I write my answer like that.
    – Alireza
    Commented May 18, 2017 at 17:41
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.