ducin
ducin

Reputation: 26467

JavaScript modify Number object (wrapper) in place - downcasting

The question is about built-in Number object (a primitive wrapper).

var n = new Number(2);
console.log(n); // Number {}
console.log(typeof n); // "object"

n++;
console.log(n); // 3
console.log(typeof n); // "number"

I can see that JS is making an implicit typecast here. Precisely, downcasting Number object to number primitive. Is there any way to modify Number object in place without such downcasting?

Upvotes: 1

Views: 121

Answers (1)

Pointy
Pointy

Reputation: 413826

No, Number instances are immutable. You'd have to do:

n = new Number(++n);

to get a new instance one bigger than a prior instance.

Upvotes: 1

Related Questions