Last Updated: February 25, 2016
·
828
· voqn

be careful about null

in javascript, defined those 5 types as primitive.

  • undefined
  • null
  • boolean : true / false
  • number: NaN / -Infinity / Infinity / 0,1,2 ... / 1.0e+3 / etc ...
  • string : '' / "" / 'hoge' / "huga" / etc ...

however, be careful about null value.

typeof null // "object" (!!)
null instanceof Object // false (!!)

typeof {} // "object"
{} instanceof Object // true

ES.next fixes this oddly specification. ECMAScript 6 is available this syntax: typeof null === 'null'.

see harmony:typeof_null

But today, typeof null return 'object'.

var isPrimitive = function(any) {
  switch (typeof any) {
    case 'undefined':
    case 'boolean':
    case 'string':
    case 'number':
      return true;
    default: // typeof any #=> 'object'
      return any === null;
  }

1 Response
Add your response

Test Markdown syntax comment

isPrimitive(true); // true
isPrimitive(0); // true
isPrimitive(null); // true
isPrimitive([]); // false
over 1 year ago ·