How To Check If Two Strings Are Not Equal In Javascript

Check if two strings are not equal in javascript

 This article will show you how to check if two strings are not equal in Javascript. In javascript, we can use not similar to check whether the value of two operands matches or not. If two operands have the same value, it returns false.

Check if two strings are not equal in Javascript ?

Comparison Operators in JS

Comparison operators in Javascript are used to compare two values. These operators return true or false base on the condition of two values and the operator.

Method 1: Not equal operator “!==” 

Not equal operator is the best way to check if two strings are similar or not. The example below will show you how it works.

Code:

//Declare two strings
var robot="Robot";
var human="Human";

//Checking if two strings are not equal
if (robot !== human) {
    console.log("robot and human are not equal");
} else {
    console.log("robot and human are equal");
}

Output:

robot and human are not equal

The output return “A and B are not equal” because “Robot” and “Human” have different values.

More example of “!==”

Code:

console.log("Robot" !== "Human");
console.log("Robot" !== "Robot"); 
console.log(5 !== 10); 
console.log(10 !== 10); 
console.log("" !== ""); 
console.log(NaN !== NaN); 
console.log(true !== true); 
console.log(false !== false); 
console.log(null !== null); 
console.log(undefined !== undefined); 

Output:

true
false
true
false 
false
true 
false
false
false
false

Method 2: Use the “!=” operator

The “!=” operator is similar to “!==,” but it uses loose inequality. The example below will show you the difference between them.

Code:

console.log("1" != 1);
console.log("1" !== 1);

Output:

false
true 

The difference between “!==” and “!=”

The difference between “!=” and “!==” is that the “!=” uses loose inequality and “!==” uses strict inequality. With loose inequality, Javascript will attempt to convert the values to the same type if the two values have different types before comparing them. That is why string “1” and integer 1 have the same value in the first part of the code.

With strict inequality in “!==”, the two values must have the same type. The comparison returns are unequal if they don’t have the same type.

Summary

To summarize, the best way to check if two strings are not equal in Javascript is not a similar operator “!==”. If two strings are not identical, it returns true.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *