Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Difference between != and !== operator in JavaScript Program
In JavaScript, != and !== are both inequality operators, but they differ in how they compare values. != performs type coercion (converts types before comparing), while !== performs a strict comparison (checks both value and type without conversion).
!= (Loose Inequality)
The != operator checks if two values are not equal after type conversion. It converts the operands to the same type before comparing their values. For example, 1 != '1' returns false because after converting the string '1' to number 1, both values are equal.
!== (Strict Inequality)
The !== operator checks if two values are not equal without type conversion. It compares both the value and the data type. For example, 1 !== '1' returns true because one is a number and the other is a string − different types means they are strictly not equal.
Key Differences
| Feature | != (Loose) | !== (Strict) |
|---|---|---|
| Type Coercion | Yes (converts types before comparing) | No (compares as-is) |
| Checks Type | No | Yes |
1 != '1' |
false |
N/A |
1 !== '1' |
N/A | true |
Example
The following example demonstrates the difference between != and !== ?
// != (loose inequality) - converts types before comparing
console.log("1 != '1' :", 1 != '1'); // false (same value after coercion)
console.log("0 != false :", 0 != false); // false (0 and false are equal)
console.log("null != undefined:", null != undefined); // false
// !== (strict inequality) - checks value AND type
console.log("1 !== '1' :", 1 !== '1'); // true (different types)
console.log("0 !== false:", 0 !== false); // true (number vs boolean)
console.log("null !== undefined:", null !== undefined); // true
// Both agree when values are truly different
console.log("1 != 2 :", 1 != 2); // true
console.log("1 !== 2 :", 1 !== 2); // true
The output of the above code is ?
1 != '1' : false 0 != false : false null != undefined: false 1 !== '1' : true 0 !== false: true null !== undefined: true 1 != 2 : true 1 !== 2 : true
Conclusion
!= performs type coercion before comparison, which can lead to unexpected results. !== compares both value and type strictly, making it more predictable and safer. It is generally recommended to use !== (strict inequality) in JavaScript to avoid type coercion bugs.
