Published Dec 18, 2020
JS has following primitives -
Ever wondered how are we able to call methods like toString() etc. on primitive values ? As, they are not like our regular objects in JS.
let name = "Ankit";
let firstChar = name.charAt(0);
console.log(firstChar); // "A"
Here we can see that we called charAt on name which is assigned a primitive value string. The second line treats name like an object and calls charAt(0) using dot notation.
Below is what happens behind the scenes or at the JS engine level -
let name = "Ankit";
let temp = new String(name);
let firstChar = temp.charAt(0);
temp = null;
console.log(firstChar) // "A"
The engine creates an instance of a String, thus the charAt(0) works. The object exists only for one statement before it’s destroyed.
Except for null and undefined, all primitive values have object equivalents that wrap around the primitive values: