1

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?

Cloudboy22
  • 1,496
  • 5
  • 21
  • 39
  • typeof null should be "object" due to a wonderful js bug that will never be fixed. I cannot for the life of me figure out why it is returning "string" in certain cases. – Jonah Williams Oct 21 '15 at 09:55
  • Possible duplicate of [why is typeof null "object"?](http://stackoverflow.com/questions/18808226/why-is-typeof-null-object) – Rahul Tripathi Oct 21 '15 at 10:03

3 Answers3

1

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.

Sk93
  • 3,676
  • 3
  • 37
  • 67
0

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

An0nC0d3r
  • 1,275
  • 13
  • 33
0

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
//=> ""
Jonah Williams
  • 20,499
  • 6
  • 65
  • 53