ChromeBrowser
ChromeBrowser

Reputation: 219

Is null a primitive type or object type?

https://developer.mozilla.org/en-US/docs/Glossary/Primitive In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. There are 6 primitive data types: string, number, bigint, boolean, undefined, and symbol. There also is null, which is seemingly primitive, but indeed is a special case for every Object: and any structured type is derived from null by the Prototype Chain.

but in Javascript the definitve guide, it says Any Javascript value that is not a number, a string, a boolean, a symbol, a null, or undefined is an object.

So which one is right? Is null an object or not.

Upvotes: 5

Views: 2750

Answers (3)

StackSlave
StackSlave

Reputation: 10627

As you can see null, Arrays, and Objects all output type 'object' when passed to typeof.

console.log(typeof null); console.log(typeof []); console.log(typeof {});

This, however, is not the same as the Object type.

If you wish to test for types like you're thinking and as defined by ECMAScript, you might want to check this out.

function getType(mixed){
  if(mixed === null){
    return 'null';
  }
  else if(mixed instanceof Array){
    return 'array';
  }
  return typeof mixed;
}

class Test{
  constructor(){
  }
  method(){
    return this;
  }
}
function ConstructorTest(){
  let privateVarsOk;
  this.method = ()=>{
    return this;
  }
}
const test = new Test; constructorTest = new ConstructorTest;

console.log(getType(null));
console.log(getType('4'));
console.log(getType(4));
console.log(getType(['a', 2, 'c']));
console.log(getType({}));
console.log(getType(getType));
console.log(getType(function(){}));
console.log(getType(()=>{}));
console.log(getType(Test));
console.log(getType(test));
console.log(getType(ConstructorTest));
console.log(getType(constructorTest));
console.log(getType());

Notice that classes are actually functions though, as they do no introduce a new hierarchy.

Upvotes: 2

RAHUL CHATTERJEE
RAHUL CHATTERJEE

Reputation: 11

var nullVar=null;
console.log("Data type of nullVar is :"+ (typeof nullVar));

o/p;-Data type of nullVar is :object

Null is primitive datatype but it returns object ... So, null return bogus return value ..

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370689

When in doubt, read the official specification, which is essentially the Word of God for JavaScript.

A primitive value is a member of one of the following built-in types: Undefined, Null, Boolean, Number, BigInt, String, and Symbol; an object is a member of the built-in type Object; and a function is a callable object. A function that is associated with an object via a property is called a method.

So, yes, null is a primitive value.

Upvotes: 10

Related Questions