JavaScript Code

How to compare two strings in JavaScript?

Compare two strings in JavaScript

In this tutorial, you are given two strings. Find a comparison between them: if first string is less than second string lexicographically, first string is greater than second string lexicographically, or if the two strings are equal in value.


To compare two strings in JavaScript, we can use comparison operators greater than, and less than.

We will use the above said operators in conditions of if-else-if statement to draw a comparison between the two given strings.


In the following program, we are given two strings in string1 and string2. We will draw a comparison between these two strings using comparison operators.

let str1 = 'apple';
let str2 = 'banana';

if ( str1 > str2 ) {
    console.log(`${str1} is greater than ${str2}`);
} else if ( str1 < str2 ) {
    console.log(`${str1} is less than ${str2}`);
} else {
    console.log('given strings are equal');