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;
Only use null if you explicitly want to denote the value of a variable as having "no value". As @com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing".
YES, you can, because undefined is defined as undefined.
JavaScript undefined Note: Usually, null is used to assign 'unknown' or 'empty' value to a variable. Hence, you can assign null to a variable.
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.
I declare them as undefined when I don't assign a value because they are undefined after all.
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.
Generally speak I defined null
as it indicates a human set the value and undefined
to indicate no setting has taken place.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With