Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does String(number) call number.toString internally?

I was just trying something and found this:

If you call String(n) inside custom toString, it calls itself and throws error Maximum Call Stack exceeded,

JSFiddle

Number.prototype.toString = function() {
  return String(this)
}

var a = 10;
try {
  a.toString()
} catch (err) {
  console.log(err.message)
}

but if you call directly var b = String(a), it does not call toString function.

JSFiddle

Number.prototype.toString = function(){
  console.log(this);
  return '' + this;
}

var a = 10;
a.toString();

Note: I know above snippet is also throwing same error, but I have checked on Node, chrome - JSFiddle and Firefox - JSFiddle and it is consistent. var b = String(a) does not call number.toString(), so does '' + this. This is some optimisation in Stack snippet thats calling number.toString() on ''+this.

So my question is, what am I missing? Why is this weird behaviour?

like image 819
Rajesh Avatar asked Dec 04 '25 11:12

Rajesh


1 Answers

Actual numbers invoke an internal method to convert them to string and their output is not affected by valueOf and toString, unless they are called explicitly.

So why is toString called in the first place then?

This is because in "sloppy" (non-strict) mode, the value of this will be converted to its object form (i.e. equivalent of new Number(10)) before being passed to String(this) or '' + this.

(For this reason, you might not see the difference between these two ways in normal applications where strict mode is used.)

As this is an object, both String() and the + addition operator will attempt to convert the object into a string. This is usually done by calling either obj.toString or obj.valueOf.

As for why String(this) fails but '' + this does not, the String function calls toString on the object before calling valueOf.

However, when you use the addition (+) operator, the order of valueOf and toString is reversed.

like image 134
Qantas 94 Heavy Avatar answered Dec 06 '25 23:12

Qantas 94 Heavy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!