Sorting strings

Suppose we have the following array:

let names = ['Ana', 'ana', 'john', 'John']; 
console.log(names.sort()); 

What do you think would be the output? The answer is as follows:

["Ana", "John", "ana", "john"] 

Why does ana come after John when a comes first in the alphabet? The answer is because JavaScript compares each character according to its ASCII value. For example, A, J, a, and j have the decimal ASCII values of A: 65, J: 74, a: 97, and j: 106.

Therefore, J has a lower value than a, and because of this, it comes first in the alphabet.

For more information about the ASCII table, visit http://www.asciitable.com.

Now, if we pass compareFunction, which contains the code to ignore the case of the letter, we will have the output ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.