Karthik Minnikanti
Karthik Minnikanti's blog

Karthik Minnikanti's blog

Why length of emoji (๐Ÿ˜œ) is 2 in JavaScript

Why length of emoji (๐Ÿ˜œ) is 2 in JavaScript

Karthik Minnikanti's photo
Karthik Minnikanti
ยทJun 17, 2022ยท

1 min read

Subscribe to my newsletter and never miss my upcoming articles

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....

ย 
Share this