1

I have read that the null data type in JavaScript is a primitive data type, however due to a bug or something in the first version JavaScript, null is considered to be an object.

However, let's assume that null is a real object (and not a primitive data type like it really is), what does that mean exactly, i.e. what does a data type being an object mean exactly?

For example if a data type is an object, does that mean that attributes and methods can be added to instances of that data type, while a primitive data type can't have attributes and methods added to its instances? and so the reasosn why null is really a primitive data type and not an object is because you can't add attributes and methods to its instances?

1 Answer 1

3

From the ECMAScript 2020 specification:

The ECMAScript language types are Undefined, Null, Boolean, String, Symbol, Number, BigInt, and Object.

And also:

The Null type has exactly one value, called null.

An Object is logically a collection of properties.

Null and Object are two different data types because that's how the spec is written. The specific bug that you are referring to is the fact that typeof null returns "object" even though it was originally intended to return "null", and this has been retained in the specification for backward compatibility.

To answer the second half of your question, objects are the only type that can have properties directly defined on them. However, since JavaScript is a prototype-based language, you can still augment other types (except Undefined and Null) with custom attributes and methods through their prototype. For example:

var x = 10; // x is a Number
x.foo = 20; // doesn't work since x is not an Object

// Number.prototype is an Object, so you can add properties to it
Number.prototype.foo = 30;
Number.prototype.bar = function() { return 40; }

x.foo; // returns 30
x.bar(); // returns 40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.