I have:
let N = new Number(42); console.log(N); // [Number: 42] console.log(N.toString()); // 42
In the second line, what does the notation using square brackets mean?
The console.log()
documentation says the “string representation” of the object argument is printed. If that is not the same as the toString()
function of the Number
object, where is the string representation of an object defined?
Afternote: I was using Node REPL.
Advertisement
Answer
That [Number: 42]
in your example is just the format used by the console you’re using to show you a Number
object that has the underlying primitive value 42
. That format varies by console. For instance, the console built into Chrome (and other Chromium-based browsers) shows Number {42}
:
If you expand it, you see more information:
It’s important to realize that new Number(42)
is a very unusual thing to do. It creates a Number
object. Normally you don’t want a Number
object, you just want a number primitive (let N = 42
or more idiomatically let n = 42
).
There are object equivalents to primitives for various reasons (String
for strings, Boolean
for booleans, etc.), but it’s rare to actually want to use them explicitly. They’re mostly there as a mechanism for specifying methods that can be accessed on the primitives, such as toFixed
on numbers, which comes from Number.prototype.toFixed
. When you use a method on a primitive, under the covers the method from the prototype object that that number would have if it were converted to its equivalent number is used. So for a primitive number, the method on Number.prototype
(the object that the equivalent number object would have) is used.
In a comment you’ve said:
From what I understand,
let n=42; console.log(n);
implicitly convertsn
to aNumber
object and then invoking itstoString
method.
Not usually, no. Usually a console has built-in handling and doesn’t use toString
, though of course this varies by console. But for example, Chrome’s console doesn’t:
Object.defineProperty(Number.prototype, "toString", { value() { return "!!!"; }, writable: true, configurable: true, }); let n = 42; // What Chrome shows: console.log(n); // 42 (shown as a number) console.log(new Number(n)); // Number {42} console.log(String(n)); // 42 (shown as a string) console.log(n.toString()); // !!!
Look at the browser's actual console.
What you see when you run that will depend on your browser, but at the moment Chrome shows: