Skip to content
Advertisement

toString() method vs string representation

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}:

Chrome console showing Number {42}

If you expand it, you see more information:

Chrome console showing a Number object showing its prototype is also a Number object and its [[PrimitiveValue]] internal slot is 42

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 converts n to a Number object and then invoking its toString 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:

Chrome console showing 42 as a number, Number {42}, 42 as a string, and then !!!

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement