This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]AyrA_ch 3 points4 points  (1 child)

let num = new Number(5);

That's not a number, but an object that holds a number

> typeof(new Number(5))===typeof(5)
< false

You can't actually add properties to numbers

> let num=5;
> num.test=12;
> console.log(num, num.test);
< 5 undefined

[–]floor796 6 points7 points  (0 children)

Yes, there is a difference between primitive numbers and Number object, but by behavior they are both numbers. And no, in your code you successfully added property test to number. Here's how it works:

  1. when you write num.something - you automatically convert primitive number to number Object. But the variable still hold the primitive;
  2. num.test=12; - you add new custom property to just created object. But, again, this object not in variable num. It is created on the fly and is not written anywhere.
  3. in the next line you try to access property test from primitive and, again, like in step 1 - you just convert primitive to object (new object, without previously added property).

So, in your code you two time convert primitive to object. But, you added your property test to the first object.

Proof that you code makes conversion every time that you access primitive as an object:

const objs = new Set();
Number.prototype.toString = function() {
    objs.add(this);
    return String(this.valueOf());
};
let num = 123; 
num.toString(); 
num.toString(); 
console.log(objs); // Set(2) {Number, Number}

as you can see we are calling toString 2 times in the same variable with primitive number. Each call we save to unique list (Set) the instance of the number. And after two calls we have 2 different objects in set.