With Comparison Operators
The inequality operator (!=) can check two string operands to see if they are not equal. It returns true if this is the case and false otherwise. Its negation is the equality operator, which can produce the same result if you use them correctly:
!(s1 == s2)
s1 != s2
The following example shows how you can implement those operators to check whether two strings are equal:
console.log('ITTutoria' != 'ITTutoria.net'); console.log(!('ITTutoria' == 'ITTutoria.net')); s = 'ITTutoria'; console.log('ITTutoria' != s); console.log(!('ITTutoria' == s));
true true false false
Keep in mind that since this is a loose comparison, those operators will convert string objects to primitives when compared to primitives.
After the conversion to primitives, the comparison goes ahead like usual if those primitives are of the same type.
const s1 = new String("ITTutoria"); const s2 = "ITTutoria"; console.log(s1 != s2); console.log(!(s1 == s2)); console.log(1 != '1');
false false false
In the above example, s1 is a String object, and s2 is a string primitive. The inequality converts the object into a primitive before carrying out the comparison.
This algorithm always works by looking at the types of the operands first. If those types are different, it considers the value unequal. If the types are the same, it checks the values themselves next. Only when operands also have the same value are they considered equal.
You can see this difference in action with this example:
const s1 = new String("ITTutoria"); const s2 = "ITTutoria"; console.log(s1 !== s2); console.log(!(s1 === s2)); console.log(1 !== '1');
true true true
Since the operands of all those operators belong to different types, the strict inequality and strict equality operators consider them different, even if they represent the same string when converted to primitives.
Choose the equality algorithm depending on how you plan to make the comparisons. Go for strict equality if you are about the type of your strings, and loose equality otherwise. The results of strict equality are more predictable, making it more recommended in most cases.
You can also use the localeCompare() method to verify the inequality of two strings. It is originally designed to check whether a string comes after or before another in alphabetical order. The method returns 0 when those strings are equivalent.
const s1 = "ITTutoria"; const s2 = "ITTutoria.net"; console.log(s1.localeCompare(s2)); console.log(s1.localeCompare("ITTutoria"));
The -1 value indicates that “ITTutoria” occurs before “ITTutoria.net”, while 0 means the s1 string and “ITTutoria” are equal.