×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

Difference between != or !== operator in JavaScript

Here, we will explore the difference between != and !== operators that are often mistakenly conceived by novice JavaScript programmers. Almost all the time it is asked in JavaScript interviews.
Submitted by Siddhant Verma, on March 06, 2020

Difference between != or !== operator in JavaScript

We can perceive the differences between these two operators as the same difference that occurs between double equalsTo (==) and triple equalsTo (===) operators. We already know that the (!) not-operator used along with (=) operator is used to check for inequalities.

let a = 10;
let b = 20;

console.log(a != b);

Output

true

Since both a and b hold different values, we get a truthy returned from the inequality.

let c = 50;
let d = 50;

console.log(c!=d);

Output

false

And of course in the above case since both have the same values != operator returns false. Therefore we can say that the != operator checks if the two variables being compared have the same value or hold the same value. If they don't, it returns true and false otherwise as we have seen in the above two examples.

let s = 101011;
let name = "sam";

console.log(s != name);
console.log(s !== name);

Output

true
true

We have compared two variables which are completely different type storing the same values and we get truthy for both the comparison expressions. Now, look at the next example:

let a1 = 10;
let a2 = "10";

console.log(a1 !== a2);
console.log(a1 != a2);

Output

true
false

In the above comparison, we're comparing two same values due to which the != operator returns us false but we're comparing two different types due to which the !== operator returns true. Thus we can say that the !== operator not only checks for the values but also for the type of the variables being compared. Since in this case both the variables had different types, they were evaluated as unequal by the !== operator and hence we got the true result.

let ob1 = { name: "Mario" }
let ob2 = { name: "Mario" }

console.log(a!=b);
console.log(a!==b);

Output

true
true

Both our objects are completely identical yet the != as well as the !== operator returns true indicating they're both unequal. Why is that so? This has something to do with the memory addressing of variables. Both the objects occupy completely different blocks of memory and are thus considered as two separate instances or two separate entities.

let ob3 = ob1;

console.log(ob1 != ob3);
console.log(ob1 !== ob3);

Output

false
false

Since now ob3 occupies the same address as ob1, they're considered completely identical. Can you conclude which out of the != and !== does a more strict comparison than the other?

JavaScript Tutorial »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.