Which came first! The π or the π₯?
Let's definitively answer this age old question by using Array.sort() and learn why the outcome is what it is.
Hi everybody - Daniel Stolbov recently answered the age old question of whether the chicken came first or the egg came first using JavaScript. In my latest video, I dive further into it and explain why the outcome is what it is:
The full code for answering this question is as follows:
let egg = "π₯";
let chicken = "π";
let arrayToSort = [egg, chicken];
let sortedArray = arrayToSort.sort();
console.log(`The ${sortedArray[0]} came first!`);
When this code runs, the console output will say that theβ¦π₯β¦chicken came first! The reason for this has to do with how emojis are represented.
Say Hello to Codepoints
The critical detail here is something known as codepoints. Codepoints are unique numerical values that identify specific characters in Unicode, including emojis. Think of them as the ID numbers for each character or emoji. For example, the "thumbs up" emoji π has the codepoint U+1F44D.
Similarly, our egg and chicken emojis have codepoint values as well:
let eggCodepoint = "π₯".codePointAt(0).toString(16);
let chickenCodepoint = "π".codePointAt(0).toString(16);
console.log(`Egg's codepoint: ${eggCodepoint}`); // 1F95A
console.log(`Chicken's codepoint: ${chickenCodepoint}`); // 1F414
The codepoint for the egg emoji is 1F95A, and the codepoint for the chicken emoji is 1F414.
When we call array.sort() on our array of emojis, our emojis are sorted by their codepoint values. Because the chicken emoji has a smaller codepoint than the egg emoji, the chicken emoji comes first. It is just a simple number sorting thing. There is no deeper meaning or insight sadly being implied here! π
Till Next Time
I hope you found this quick JavaScript sorting tip, disguised as a fun exercise, helpful and entertaining.
As always, I like to hear from you. To discuss this further, feel free to continue the conversation on my Twitter / X post on this or on the forums.
Cheers,
Kirupa π
Chicken or the egg?
The first amniotic eggs preceded Chickens by at least
340 Millions of years