Home > Back-end >  Can I use a string argument whenever MDN use the term "Number" argument?
Can I use a string argument whenever MDN use the term "Number" argument?

Time:07-05

While reading Intl.NumberFormat.prototype.format, I found out that the function can format a numeric string. However, in its syntax docs, only Number and BigInt are listed as valid argument types.

My question: Is this applies to every JS functions accepting a Number object?

CodePudding user response:

A lot of built-in objects, methods, and functions are pretty loose with their types. Often, if you pass a type that isn't, strictly speaking, sensible to use with the method, the engine will attempt to coerce it for you. That's what's happening here too.

The behavior is specified:

When a Number format function F is called with optional argument value, the following steps are taken:

...

  1. Let x be ? ToNumeric(value).
  2. Return ? FormatNumeric(nf, x).

Can you always rely on this sort of coercion in general? No - but many things have been designed so that they work even with sloppy code, especially built-ins.

Code written in JavaScript (and not in the engine's underlying implementation) is, in general, significantly less likely to be tolerant of type problems. For example

const hasSubstring = (str, sub) => str.includes(sub)

will throw an error when called with a number, because Number.prototype.includes doesn't exist.

  • Related