JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to check if two strings are equal or not in JavaScript?

JavaScript provides two operators == and === to check whether two strings are equal or not.

The === operator is a strict equality operator and returns true when both operands are of the same type and have the same value. On the other hand, the == operator checks whether the two values are the same or not and is least concerned with their type.

The following example explains to you the difference between == and === operators.

let str1 = '123';
let str2 = 123;

console.log("Equality test using == operator");
if(str1 == str2){
  console.log('Equal');
}else{
  console.log('Not Equal')
}

console.log("Equality test using === operator");
if(str1 === str2){
  console.log('Equal');
}else{
  console.log('Not Equal');
}

Output

Equality test using == operator
Equal
Equality test using === operator
Not Equal

As you can see, the == operator does not check the type of the operands, whereas the === operator checks the type of the operands. Therefore, it is recommended that you use the === operator in checking the equality of two strings.

When the string in your have characters of different languages such as French, German, and others, then to check the equality of strings, call the normalize() method on the strings and then use the === operator for equality.

JavaScript String Equality

Output

Equal