3

Is it actually possible to get the Null data type as a return from the typeof function - if so what case yields that result, when is a variable actually of the Null type?

    typeof myVAR; //gives me "undefined" before the variable declaration

    var myVAR;
    typeof myVAR; //also gives me "undefined"

    myVAR = null; //assigned the null object
    typeof myVAR; //gives me "Object" (which I guess makes sense because `null` is an object and that's what I assigned to the variable)
Suvi Vignarajah
  • 5,758
  • 27
  • 38
  • 1
    possible duplicate of [Why is null an object and what's the difference between null and undefined?](http://stackoverflow.com/questions/801032/why-is-null-an-object-and-whats-the-difference-between-null-and-undefined) – PSL Oct 15 '13 at 00:18
  • @PSL not quite, that explains what the `null` value is - but my question is geared more towards `Null` (the data type)? – Suvi Vignarajah Oct 15 '13 at 01:46
  • Ok. I shall retract my close vote. – PSL Oct 15 '13 at 01:48

1 Answers1

8

typeof never returns "null", but there is an internal null type:

Typeof Results:

  • Undefined: "undefined"
  • Null: "object"
  • Boolean: "boolean"
  • Number: "number"
  • String: "string"
  • Object (native and does not implement [[Call]]): "object"
  • Object (native or host and does implement [[Call]]): "function"
  • Object (host and does not implement [[Call]]): Implementation-defined except may not be "undefined", "boolean", "number", or "string".

The only way to test for null would be a direct comparison with the null value, using the === operator.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
  • hmm..thank you, that answers part of my question, but can a variable ever be of `Null` data type? – Suvi Vignarajah Oct 15 '13 at 01:34
  • @SuviVignarajah: A variable can have the `null` value, which is the only value of the `Null` data type. – Qantas 94 Heavy Oct 15 '13 at 02:22
  • I understand now - I did some research, seems like the `Undefined` data types "special" value is also `undefined` (similar to `Null` and `null`). You can declare a variable `var myVAR = undefined`, and `typeof myVAR` will yield `undefined` still. Seems like the `typeof` in javascript just doesn't return `Null` or `null` as one of the types like you state in your answer. – Suvi Vignarajah Oct 15 '13 at 02:59
  • @SuviVignarajah: typeof doesn't return the actual name of the internal type - that may be slightly confusing. – Qantas 94 Heavy Oct 15 '13 at 03:02
  • Slightly..on another note, this explanation [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#null) gives me some closure though about why `typeof null` yields `"object"`. – Suvi Vignarajah Oct 15 '13 at 03:14