Javascript charAt() method on string & character comparison operators

Hi, I reached the exercise 7 of Debugging with console.log() where I got a question. In the exercise we have to debug the code given, so trying to figure out how to repair the code I realize one thing that I didn’t know and I hope this is how I think it works.

This is the code of the exercise:

// Returns the string whose first letter is later in the alphabet. If both first letters are equal, returns null.
function getLaterFirstLetter(string1, string2) {
  
  const firstLetter1 = string1.charAt(0);
  const firstLetter2 = string2.charAt(0);
 
  if (firstLetter1 === firstLetter2) { 
    return null;
  } else if (firstLetter1 < firstLetter2) { // 
    return string2;
  } else {
    return string1;
  }
}

// Should return "blueberry"
console.log("getLaterFirstLetter('avocado', 'blueberry') returns: " + getLaterFirstLetter('avocado', 'blueberry'));

// Should return "zebra"
console.log("getLaterFirstLetter('zebra', 'aardvark') returns : " + getLaterFirstLetter('zebra', 'aardvark'));

// Should return null
console.log("getLaterFirstLetter('astro', 'afar') returns: " + getLaterFirstLetter('astro', 'afar'));

How Comparison Operators works with the characters firstLetter1 and firstLetter2? I mean, I think before this exercise that comparison operator works only with number. How the computer knows that the character “a” it’s less than “z”?

Thanks and sorry for my English. I’m trying to improve. :slight_smile:

When comparing string objects, the operator parses out the first letter of one, and the first letter of the other, then compares the two. It knows which comes before which by its character code. We know that ‘A’ comes before ‘B’ (or ‘Z’) in the alphabet (a human construct). The computer knows which is first by which has the smallest character code. A => 65; B => 66; Z => 90.

Bottom line, with numbers, < is, a less than b; with strings, < is, a comes before b.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.