3

I took a JS course on a website , and in one of the lessons there was a piece Of code that did not make sense to me :

enter image description here

the code is in the picture , why str1 is less then str2 ?

5
  • 1
    Can you include text of javascript at Question? Commented Feb 9, 2017 at 16:59
  • 2
    Because a comes before b. en.wikipedia.org/wiki/Alphabetical_order , en.wikipedia.org/wiki/Lexicographical_order Commented Feb 9, 2017 at 16:59
  • the strings are compared in character by character mode and every character has its code (Unicode) representation. Finally, it is the charatcters' codes in both strings that get compared. Commented Feb 9, 2017 at 17:00
  • "a".codePointAt(0) => 97 , "b".codePointAt(0) => 98 Commented Feb 9, 2017 at 17:05
  • Possible duplicate of How does string comparison work in JavaScript? Commented Feb 9, 2017 at 17:08

3 Answers 3

2

Strings are compared based on standard lexicographical ordering, using Unicode values. That means "a" < "b" and "c" > "b"

Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions. source

var str1 = "aardvark";
var str2="beluga";
console.log(str1 < str2);//true
console.log(str1.length < str2.length);//false

Sign up to request clarification or add additional context in comments.

Comments

0

This compares each character from 0-index, for example "a"<"b" thi is true. If there are equal, it compares next index, and next, ... "aad">"aac", because, twice "a"="a" and then "d">"c"

Comments

0

JavaScript in this case will compare the strings lexographically character by character, where the letter 'a' is lower than the letter 'b' and so on. It works for numbers too, and the uppercase alphabet is considerd higher than the lowercase alphabet.

So, in your example, 'a' < 'b' and therefore the statement is true.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.