Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

Today, I’m going to show how do you check if a string is equal to another string in javascript, here I will use the == and === operator to compare strings and check whether both are equal or not.

  • The == in JavaScript is used for comparing two variables, but it ignores the data type of variable.

  • The === is used for comparing two variables, but this operator also checks datatype and compares two values.

Let’s start today’s tutorial How to check if a string is equal to another string in javascript?

Here, we will take the example of both operators and see how we can use them to compare one string to another string.

We are going to do,

  1. Create a sample string variable
  2. Use the == operator to compare string
  3. Use the === operator to compare string
  4. Console comparison output
// Create sample string variable
const str1 = "infintbility";
const str2 = "1";

// Use the `==` operator to compare string
// Console comparison output
console.log(str1 == "infintbility"); // true
console.log(str1 == "invalid-string"); // false

console.log(str2 == "1"); // true
console.log(str2 == 1); // true

// Use the `===` operator to compare string
// Console comparison output
console.log(str1 === "infintbility"); // true
console.log(str1 === "invalid-string"); // false

console.log(str2 === "1"); // true
console.log(str2 === 1); // false

Run the above program, you can easily understand it after reading the above example.

let’s check the output.

javascript, check if a string is equal to another string example
javascript, check if a string is equal to another string example

I hope it’s help you, All the best 👍.