JavaScript Code

How to compare two strings in JavaScript?


Problem Statement

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

Solution

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

Program

given two strings are string1 and string2. draw a comparison between these two strings

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');
}