Cloudboy22
Cloudboy22

Reputation: 1514

Typeof operator resturns a string than null

I am a newbie to Js. Now I have this code

var name = null;
console.log(typeof name);

But the result is a string? why is that? why not null?

Upvotes: 1

Views: 79

Answers (3)

Sk93
Sk93

Reputation: 3718

In JavaScript, the data type of null is actually an object, rather than actually being null.

Because of this, when you call typeof, it will return a string of "undefined" (or "null"), rather than the null value you're expecting.

You can read more about how JavaScript handles it on the official specifications.

JavaScript values were initially represented as a tag and a value, with the tag for objects being 0, and null was represented as the standard null pointer. This led to problems with typeof returning a tag of 0 for nulls.

Because of this, this statement will always pass as true:

 typeof null === 'object';

There was a proposed fix for this, but it was rejected as it would have caused problems with existing code that used this "trick" to validate nulls.

Upvotes: 1

Jonah Williams
Jonah Williams

Reputation: 21431

It seems to have something to do with a global variable wherever you are running your code. Due to a longstanding bug that will never be fixed, the typeof a null reference is evaluated to object.

var a = null;
typeof a
// => "object"

However, in certain environments it appears that the specific variable name is set to the values such as "null" or "", meaning it would evaluate to string

name
//=> "null"
typeof name
//=> "string"

To try this out, go ahead an open a javascript console on stackoverflow and type

name
//=> ""

Upvotes: 0

An0nC0d3r
An0nC0d3r

Reputation: 1303

Although it returns "null", that is purely typeof's way of informing you what it's type is... it's not actually returning us a type of the type your testing, does that make sense?

Test any type and it will return it as a "string", "object" etc

Upvotes: 0

Related Questions