var num1 = new Number(5);
typeof(num1); //returns "object"
num1.toString(); //returns "5"
I understand that num1
being an object has a property .__proto__
via which it gets access to .toString()
by going down the prototype (.__proto__
) chain.
var num = 5;
typeof(num); //returns "number"
num.toString(); //returns "5"
In above case, num is a primitive type number
. It means that it won't have any properties and methods. Then how's it able to get access to .toString()
method?
What Are Primitive Types in JavaScript? There are 6 primitive types (or “primitive data types”) in JavaScript: numbers, strings, booleans, bigints, symbols, and undefined. Primitive types are not JavaScript objects.
We will study those soon, but first we’ll see how it works because, of course, primitives are not objects (and here we will make it even clearer). Let’s look at the key distinctions between primitives and objects. Is a value of a primitive type. There are 7 primitive types: string, number, bigint, boolean, symbol, null and undefined.
There are two types of datatypes in JavaScript: Primitive and Non-Primitive. Primitive defines immutable values and was introduced recently by ECMAScript standard.
In other words, there are no “mutator methods” for primitives like there are for arrays, which have methods like .sort () ( Array.prototype.sort ()) that actually change the array. When we call .toUpperCase () ( String.prototype.toUpperCase ()) on a string, we get back a new string — but the existing string never changes.
It means that it won't have any properties and methods.
Javascript has a property called coercion when it comes to primitives; it silently converts the primitive to any object and then accesses the prototype method of the newly constructed number object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With