Note: I am not looking for opinions. A single, objective useful example of a primitive constructor would satisfy the question.
Are there any good reasons to use new Number(n)
? Why does this constructor exist?
I can think of several reasons to avoid it, eg.,
- literals are more memory efficient since they don't construct anything new.
- literals are equal to each other (
5 === 5
butnew Number(5) !== new Number(5)
). - the
typeof
operator indicates that it's a number/str/etc rather than an object. new Number(0)
is never falsey. (!!new Number(false) == true
).- You can use it for type conversion, but there are more concise methods. (
+false === 0
).
To be clear, I understand the Number object (or String or Object or Array objects) has useful methods and properties, my question is specifically about the constructor.
I am also aware that the constructors are called implicitly when using the methods of these primitive types (eg. 123.45.toFixed(n)
), but that doesn't explain why the constructors are exposed to the browser, or how (or if) the constructors themselves are useful.
I'm using Number as an example, but I don't understand why Javascript exposes other constructors where literals are available either (String, Object, Array, etc.).
Why do these exist and are there ever any good reason to use them?