Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does primitive types in Javascript have methods and Properties? [duplicate]

Tags:

javascript

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?

like image 547
Himansh Avatar asked Nov 05 '18 06:11

Himansh


People also ask

What are primitive types in JavaScript and how to use them?

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.

What is the difference between primitives and 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.

What are the different types of datatypes in JavaScript?

There are two types of datatypes in JavaScript: Primitive and Non-Primitive. Primitive defines immutable values and was introduced recently by ECMAScript standard.

Are there any mutator methods for primitives in JavaScript?

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.


1 Answers

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.

like image 84
Derek Brown Avatar answered Oct 18 '22 15:10

Derek Brown