Before finding the Length of an Emoji, Lets get answers for some Imp Questions
How Javascript Stores String?
Before storing any string into memory, String is converted into 16-bit long binary numbers and JS engine uses UTF-16 string formatting to store characters.
Know more about UTF-16 here
#Example
const s = "😜"
s[0] ---> '\uD83D'
s[1] ---> '\uDE1C'
How Length of a string is Calculated?
Whenever the .length property is accessed, JavaScript looks up and returns the number of code units occupied by the string. Which means it returns the length of Uint16Array.
Lets prove it in the code.
#code
const encoder = new TextEncoder()
const view = encoder.encode('😜')
const ar8 = new Uint8Array(view);
const buf = new Buffer(ar8);
const ar16 = new Uint16Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint16Array.BYTES_PER_ELEMENT);
console.log("Array Length",ar16.length);
console.log("Emoji Length","😜".length)
#output
Array Length 2
Emoji Length 2
LHS = RHS
Hence Proved....
Â