Difference Between == and === in JavaScript

Difference between == and === in JavaScript

=== and !== are strict comparison operators:

JavaScript has both strict and
type-converting equality comparison.
For strict equality the objects being
compared must have the same type and:

  • Two strings are strictly equal when they have the same sequence of
    characters, same length, and same
    characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have
    the same number value). NaN is not
    equal to anything, including NaN.
    Positive and negative zeros are equal
    to one another.
  • Two Boolean operands are strictly equal if both are true or
    both are false.
  • Two objects are strictly equal if they refer to the same Object.
  • Null and Undefined types are == (but not ===). [I.e. (Null==Undefined) is true but (Null===Undefined) is false]

Comparison Operators - MDC

Difference between != and !==

= is an assignment operator, e.g. If you run var x = 1; then x will have the value of 1.

== (or !=) is a comparison operator that checks if the value of something is equal to the value of something else. e.g. if(x == 1) will evaluate to true and so will if(x == true) because 1 will evaluate to true and 0 evaluate to false.

=== (or !==) is another comparison operator that checks if the value of something is equal to the value of, and is the same type as something else. e.g. if(x === 1) will evaluate to true however, if(x === true) will evaluate to false because 1 (the value of x) is an integer and true is a boolean.

What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)

= is the assignment operator. It sets a variable (the left-hand side) to a value (the right-hand side). The result is the value on the right-hand side.

== is the comparison operator. It will only return true if both values are equivalent after coercing their types to the same type.

=== is a more strict comparison operator often called the identity operator. It will only return true if both the type and value of the operands are the same.

I would check out CodeCademy for a quick intro to JavaScript.

If you prefer to read more, MDN is a great intro as well.

For those concerned about the source of the term "identity operator" jbabey pointed out that JavaScript: The Definitive Guide seems to mention it.

What is the difference between == and === in JavaScript?

  • == attempts to convert the values to the same type before testing if they're the same. "5" == 5
  • === does not do this; it requires objects to be of the same type to be equal. "5" !== 5

In this case, the result is:

  • x == undefined will be true if x is undefined or null.
  • x === undefined will only be true if x is undefined.

You should prefer the first method if you'd like undefined and null to be treated equivalently. One common use of this is optional function arguments.

function greet(name, greeting) {
if (name == undefined) name = 'World';
if (greeting == undefined) greeting = 'Hello';
alert(greeting + ' ' + name);
}

greet(); // alerts "Hello World"
greet("Bob"); // alerts "Hello Bob"
greet(null, "Goodbye"); // alerts "Goodbye World"

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

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

Reference: Javascript Tutorial: Comparison Operators

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

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

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

'' == '0'           // false
0 == '' // true
0 == '0' // true

false == 'false' // false
false == '0' // true

false == undefined // false
false == null // false
null == undefined // true

' \t\r\n ' == 0 // true

Equality Comparison Table

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


Update:

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

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

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

var e = "text";
var f = "te" + "xt";

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

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

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

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

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

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

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

what is the difference between != and !== in Javascript?

!== and === are strict comparison, and == / != are loose comparison. It's best to use strict comparison.

JavaScript performance difference between double equals (==) and triple equals (===)

Strict comparison (===) will always be slightly faster, but the difference is usually negligible.

It definitely makes sense to prefer === if you know for certain that you don't need type coercion in the comparison. It will always be at least as fast as ==.

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

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

Reference: Javascript Tutorial: Comparison Operators

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

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

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

'' == '0'           // false
0 == '' // true
0 == '0' // true

false == 'false' // false
false == '0' // true

false == undefined // false
false == null // false
null == undefined // true

' \t\r\n ' == 0 // true

Equality Comparison Table

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


Update:

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

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

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

var e = "text";
var f = "te" + "xt";

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

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

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

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

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

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

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

Should I use == or === In Javascript?

Using == compares only the values, === compares the type of the variable also.

1 == 1 -> true
1 == "1" -> true
1 === 1 -> true
1 === "1" -> false, because 1 is an integer and "1" is a string.

You need === if you have to determine if a function returns 0 or false, as 0 == false is true but 0 === false is false.

Why use triple-equal (===) in TypeScript?

Imagine you're designing TypeScript from scratch. Essentially, you're trying to optimize for making safer code easier to write (TypeScript design goal 1) with a few caveats which prevent you from doing everything you'd like.

JavaScript compatibility (TypeScript design goal 7)

JavaScript should be valid Typescript with no changes.

CoffeeScript makes no guarantees regarding this, so it can convert all instances of == to === and simply tell users don't rely on =='s behavior. TypeScript cannot redefine == without breaking all JavaScript code that relies on its behavior (despite this having sad implications for 3).

This also implies that TypeScript cannot change the functionality of === to, for example, check the types of both operands at compile time and reject programs comparing variables of different types.

Further, compatibility is not limited to simply JavaScript programs; breaking compatibility also affects JavaScript programmers by breaking their assumptions about the differences between == and ===. See TypeScript non-goal number 7:

Introduce behaviour that is likely to surprise users. Instead have due consideration for patterns adopted by other commonly-used languages.

JavaScript as the target of compilation (TypeScript design goal 4)

All TypeScript must be representable in JavaScript. Further, it should be idiomatic JavaScript where possible.

Really though, the TypeScript compiler could use methods returning booleans for all comparisons, doing away with == and === entirely. This might even be safer for users: define a type-safe equality method on each TypeScript type (rather like C++ operator==, just without overloading).

So there is a workaround (for users comparing classes). unknown or any variables can have their types narrowed before using the type-safe equality method.

Which to prefer

Use === everywhere you would in JavaScript. This has the advantage of avoiding the pitfalls common to ==, and doesn't require you to maintain an additional method. The output of the TypeScript compiler will be close to idiomatic JavaScript. Using == has very much the same pitfalls as JavaScript, particularly when you have any, [], or {} involved. As an exception, using == null to check for null or undefined may save headaches if library code is inconsistent.

A method for reference equality (behavior like === for classes) could be confused with a deep/value recursive equality check. Furthermore, === is widely used in TypeScript, and making your code fall in line with conventions is usually more important than any small bit of type safety.



Related Topics



Leave a reply



Submit