Skip to content Skip to sidebar Skip to footer

In JavaScript, If “Strings Are Objects” Then Why Not Numbers Too?

You can do 'a'.charAt(0); wouldn't it be nice if you could do: 42.isMeaningOfLife(); well, or rather something more practical like myNumber.round(); Sure the first thing that c

Solution 1:

I believe it's a simple matter of supported syntax. Both, strings and numbers are wrapped in their respective object wrapper (String, Number) when performing objects operations on them.

Number.prototype.isTheMeaningOfLife = function () {
    return this.valueOf() === 42;
};

(42).isTheMeaningOfLife(); //true
42.0.isTheMeaningOfLife(); //true

Post a Comment for "In JavaScript, If “Strings Are Objects” Then Why Not Numbers Too?"