Check if two Strings are NOT equal
To Check if two Strings are NOT equal:
Use The strict inequality (!==) operator checks if two strings are not equal to one another. For example, if string a is not equal to string b, then a !== b.
The strict inequality operator returns true if the two strings being compared are not equal, and false if they are equal.
Example –
const a = 'StringOne';
const b = 'StringTwo';
if (a !== b) {
console.log('The strings are NOT equal');
} else {
console.log('The strings are equal');
}
Here’s what the above code is doing:
- We’re creating two variables, a and b, and assigning them the strings ‘StringOne’ and ‘StringTwo’ respectively.
- We’re using the strict inequality (!==) operator to check if a is NOT equal to b.
- If a is NOT equal to b, we log ‘The strings are NOT equal’ to the console.
Always remember, The strict inequality (!==) operator returns a boolean result:
true
if the operands are not equalfalse
if the operands are equal
The strict inequality (!==) operator is the negation of the strict equality (===) operator.
Let’s explore this idea with an example.
console.log(5 !== '5');
console.log('one' !== 'one');
console.log('one' !== 'ONE');
console.log('' !== ' ');
console.log(null !== null);
console.log(undefined !== undefined);
console.log(NaN !== NaN);
The strict inequality (!==) operator returns true
if the operands are not equal and/or not of the same type and returns false if the operands are equal and/or of the same type.
The strict inequality (!==) operator considers two values to be different if they are of different types, as opposed to the loose inequality (!=) operator which does not consider type when determining if two values are different.
The strict inequality operator will never return true
if the two values being compared are of different types.
It is always recommended to use strict operators (!==, ===) when comparing values, as they do not try to coerce the values to the same type before comparison. This produces more intuitive results.
The last example shows that NaN !== NaN
is true. This is because NaN
is the only value in JavaScript that is not equal to itself.