Set JavaScript variable = null, or leave undefined?


When declaring variables at the top of the JavaScript function, is it best practice to set them equal to null, or leave as 'undefined'? Another way to ask, what circumstances call for each option below?

Option A:

var a = null,
    b = null;

Option B:

var a,

This question is tagged with javascript

~ Asked on 2013-05-10 03:37:25

The Best Answer is


I declare them as undefined when I don't assign a value because they are undefined after all.

~ Answered on 2013-05-10 03:39:57


It depends on the context.

  • "undefined" means this value does not exist. typeof returns "undefined"

  • "null" means this value exists with an empty value. When you use typeof to test for "null", you will see that it's an object. Other case when you serialize "null" value to backend server like mvc, the server will receive "null", but when you serialize "undefined", the server is unlikely to receive a value.

~ Answered on 2013-05-10 03:52:50

Most Viewed Questions: