Last Updated: February 25, 2016
·
989
· 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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside