Set JavaScript variable = null, or leave undefined?

57

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,
    b;

This question is tagged with javascript

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

The Best Answer is


22

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


45

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 asp.net 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: