简体   繁体   中英

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.

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.

As you can see null, Arrays, and Objects are all Objects.

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

If you wish to test for types like you're thinking, 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 class es are actually functions though, as they do no introduce a new hierarchy.

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM