Reputation: 1143
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;
Upvotes: 75
Views: 241541
Reputation: 1397
Generally speak I defined null
as it indicates a human set the value and undefined
to indicate no setting has taken place.
Upvotes: 10
Reputation: 3458
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:
var a, b = null;
c = {a, b};
console.log(c);
console.log(JSON.stringify(c)) // a omited
*or some utility function/library that works in similar way or uses JSON.stringify
underneath
Upvotes: 3
Reputation: 71
There are two features of null we should understand:
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
Upvotes: 1
Reputation: 51
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.
Upvotes: 5
Reputation: 961
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.
Upvotes: 16
Reputation: 6269
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
.
Upvotes: 3
Reputation: 48982
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.
Upvotes: 62
Reputation: 17299
I declare them as undefined when I don't assign a value because they are undefined after all.
Upvotes: 28