Actually, numbers are object literals. It's just that you need to put parentheses around the number so the console finishes parsing the number. This way, the .
isn't mistaken for a decimal point. You can also put .
s, one for a decimal point and one for the .toString()
:
//This outputs "2":
console.log((2).toString());
//So does this:
console.log(2..toString());
var hello = 2;
//So does this:
console.log(hello.toString());
For more on this parsing error, go check out @vihan's answer.
In JavaScript, there is a prototype for every type. For true
and false
, there is the Boolean
prototype. For numbers like 1
, there is the Number
prototype. For strings like "Hi!"
, there is the String
prototype. However, Booleans, numbers, and strings are all primitive objects, meaning they are immutable, meaning that you can't set properties on them like regular objects:
var hello = 2;
//hello is a Number object and can have properties and methods like .toString():
console.log(hello.toString());
//This doesn't work, however, because while hello is an object, it is immutable:
hello.hello = 2;
//This outputs undefined because the above didn't work:
console.log(hello.hello);
In contrast, arrays (from the Array
prototype), functions (from the Function
prototype), are mutable objects, so you can set properties on them just fine. Also, regular objects like {regular: true}
descend from the Object
prototype and are also mutable.
var arr = [1, 2];
//arr is mutable, so this works just fine and outputs 2:
arr.hello = 2;
console.log(arr.hello);
Thus, all literals in JavaScript are objects, but some are mutable while others are immutable. You can also make regularly mutable objects immutable with Object.freeze()
, but making mutable objects immutable is even more complicated.
It should be noted that all of these prototypes -- Boolean
, String
, Number
, Array
, Function
-- descend from Object
. This is because all prototypes are objects themselves and must thus descend from Object
. This is like how in Java where all classes descend from Object
somehow. However, there is a way to get rid of descending from Object
using __proto__
, but that's EVEN MORE CONFUSING and it's probably not good to get into that if you're just getting into JavaScript.
I hope this explanation has helped you understand JavaScript better!