[javascript] 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,
    b;

This question is related to javascript

The answer is


Generally, I use null for values that I know can have a "null" state; for example

if(jane.isManager == false){
  jane.employees = null
}

Otherwise, if its a variable or function that's not defined yet (and thus, is not "usable" at the moment) but is supposed to be setup later, I usually leave it undefined.


There are two features of null we should understand:

  1. null is an empty or non-existent value.
  2. null must be assigned.

You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value.

example:-

 let a = null;
 console.log(a); //null

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.


You can use ''; to declaring NULL variable in Javascript


The only time you need to set it (or not) is if you need to explicitly check that a variable a is set exactly to null or undefined.

if(a === null) {

}

...is not the same as:

if(a === undefined) {

}

That said, a == null && a == undefined will return true.

Fiddle


Be careful if you use this value to assign some object's property and call JSON.stringify later* - nulls will remain, but undefined properties will be omited, as in example below:

_x000D_
_x000D_
var a, b = null;_x000D_
_x000D_
c = {a, b};_x000D_
_x000D_
console.log(c);_x000D_
console.log(JSON.stringify(c)) // a omited
_x000D_
_x000D_
_x000D_

*or some utility function/library that works in similar way or uses JSON.stringify underneath


I usually set it to whatever I expect to be returned from the function.

If a string, than i will set it to an empty string ='', same for object ={} and array=[], integers = 0.

using this method saves me the need to check for null / undefined. my function will know how to handle string/array/object regardless of the result.


Generally speak I defined null as it indicates a human set the value and undefined to indicate no setting has taken place.