You probably heard at least once this assertion “In JavaScript, everything is an object”. There are some reasons for this statement, but in fact, this statement is a misconception. The truth is that most of the values in JavaScript can behave like objects, but this doesn’t make them objects.
Primitive Types
ECMAScript® Language Specification tells us straight off that JavaScript has primitive types. It has 7 built-in types, which are:
undefined
null
bolean
string
number
symbol
object
All of these types except object
are primitives, so according to specification definitely, not everything is an object in JavaScript.
6.1ECMAScript Language Types
An ECMAScript language type corresponds to values that are directly manipulated by an ECMAScript programmer using the ECMAScript language. The ECMAScript language types are Undefined, Null, Boolean, String, Symbol, Number, and Object. An ECMAScript language value is a value that is characterized by an ECMAScript language type.
Boxing
Primitive values don’t have properties or methods, so you may wonder how it’s possible that we can access properties or call methods on primitives.
const text = 'hello'; text.length; // 5; text.toUpperCase(); // HELLO;
This behavior is called boxing and it’s a form of implicit coercion. In short, when you try to access a property or call a method on a primitive value JavaScript tries to be super helpful and make it into an object for you. Let’s imagine a world in which JavaScript has no boxing, then the code above might look like this:
const text = 'hello'; new String(text).length; // 5 new String(text).toUpperCase(); // HELLO
Wrapping up
Boxing is a thing that might give us this false impression that everything in JavaScript is an object, but as you can see the truth is slightly different. It allows most of the values to behave like objects, but it doesn’t make them objects. Also, specification tells us clearly that not everything is an object in JavaScript world. This simple example shows us that it’s always a good practice to check the specification rather than try to build our own theories based on what we observe and how things behave. What we might think is happening under the hood and what is really going on could be two different things.