How to compare two strings in javascript if condition?

There are many methods in Javascript by which we can compare two strings. Such as Abstract Equality Comparison (==) and Strict Equality Comparison (===).

The strict equality operator (===) behaves identically to the abstract equality operator (==) except no type conversion is done, and the types must be the same to be considered equal.

so using === is always the recommended approach.

string1 = "hello";
string2 = "hello";

if (string1 === string2) {
  console.log("Matching strings");
}else{
  console.log("Strings do not match");
}

Result

Matching strings

Strict equality using ===

var num = 0;
var obj = new String('0');
var str = '0';

console.log(num === num); // true
console.log(obj === obj); // true
console.log(str === str); // true

console.log(num === obj); // false
console.log(num === str); // false
console.log(obj === str); // false
console.log(null === undefined); // false
console.log(obj === null); // false
console.log(obj === undefined); // false