0

Can someone explain why this is the case?

console.log('AB_CD' > 'AB_C_D'); //false
console.log('ab_cd' > 'ab_c_d'); //true

4
  • 3
    "A".charCodeAt(0) -> 65; "a".charCodeAt(0) -> 97; "_".charCodeAt(0) -> 95 Commented Mar 1, 2021 at 9:13
  • 1
    Because _ is larger than any upper-case letter but smaller than any lower-case letter, i.e. 'D' < '_' (first line) but 'd' > '_' (second line) Commented Mar 1, 2021 at 9:14
  • Check the ascii table Commented Mar 1, 2021 at 9:14
  • I see... haven't thought '_' is in between... thanks guys! Commented Mar 2, 2021 at 0:17

1 Answer 1

2

Strings are compared using character codes, which you can learn more about reading this tutorial

In this first comparison ('AB_CD' > 'AB_C_D'), the character code for D and _ are 68 and 95, respectively, which explains why the expression evaluates as false.

A: 65; A: 65
B: 66; B: 66
_: 95; _: 95
C: 67; C: 67
D: 68; _: 95

In the second comparison ('ab_cd' > 'ab_c_d'), the character code for d and _ are 100 and 95, respectively, which explains why the expression evaluates as true.

a: 97;  a: 97
b: 98;  b: 98
_: 95;  _: 95
c: 99;  c: 99
d: 100; _: 95
Sign up to request clarification or add additional context in comments.

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.