NOT everything in JavaScript is an object.
All data in JavaScript must fall into one of six primitive types or object types. Primitive types include boolean, null
, undefined
, string, number, and character; everything that is not primitive is an object .
This means that functions are objects, arrays are objects, ES6 de-sugar classes into functions that are objects.
The confusion arises because primitive values have wrappers on objects. When you try to access the length
property in a string literal, JavaScript creates a temporary wrapper for the object around the primitive and accesses the length property of the wrapper for that object. After the property has been restored, the wrapper of the object is discarded. This is called auto-boxing.
Essentially, it is implemented similarly to the following:
const foo = "bar";
or
const foo = "bar"; (new String(foo)).length;
String, number, and boolean primitives have object wrappers, but null
and undefined
do not. Therefore, an attempt to access a property or method from these primitives will cause an error.
null.length; // Uncaught TypeError: Cannot read property 'length' of null undefined.length; // Uncaught TypeError: Cannot read property 'length' of undefined
source share