When do I initialize variables in JavaScript with null or not at all?

62,246

Solution 1

The first example doesn't assign anything to the variable, so it implicitly refers to the undefined value (see 10.5 in the spec for the details). It is commonly used when declaring variables for later use. There is no need to explicitly assign anything to them before necessary.

The second example is explicitly assigned null (which is actually of type null, but due to a quirk of the JavaScript specification, claims to have type "object"). It is commonly used to clear a value already stored in an existing variable. It could be seen as more robust to use null when clearing the value since it is possible to overwrite undefined, and in that situation assiging undefined would result in unexpected behaviour.

As an aside, that quirk of null is a good reason to use a more robust form of type checking:

Object.prototype.toString.call(null); // Returns "[object Null]"

Solution 2

I just saw this link which clarified my question. What reason is there to use null instead of undefined in JavaScript?

Javascript for Web Developers states "When defining a variable that is meant to later hold an object, it is advisable to initialize the variable to null as opposed to anything else. That way, you can explicitly check for the value null to determine if the variable has been filled with an object reference at a later time."

Solution 3

I don't think there's a particular better way of doing things, but I'm inclined to avoid undefined as much as possible. Maybe it's due to a strong OOP background.

When I try to mimic OOP with Javascript, I would generally declare and initialize explicitly my variables to null (as do OOP languages when you declare an instance variable without explicitly initializing it). If I'm not going to initialize them, why even declare them in the first place? When you debug, if you haven't set a value for a variable you watch, you will see it as undefined whether you declared it or not...

I prefer keeping undefined for specific behaviours:

  • when you call a method, any argument you don't provide would have an undefined value. Good way of having an optional argument, implementing a specific behaviour if the argument is not defined.
  • lazy init... in my book undefined means "not initialized: go fetch the value", and null means "initialized but the value was null (eg maybe there was a server error?)"
  • arrays: myArray[myKey] === null if there is a null value for this key, undefined if a value has never been set for this key.

Be careful though, that myVar == null and myVar == undefined return the same value whether myVar is undefined, null or something else. Use === if you want to know if a variable is undefined.

Solution 4

I would explicitly choose null, to not create an object whose id is later overwritten anyway:

var foo = {}; // empty object, has id etc.
var foo2 = null; // good practice, // filled with an object reference at a later time
var foo3;// undefined, I would avoid it
console.log(typeof foo);
console.log(typeof foo2);
console.log(typeof foo3);

Setting null also ensures good readability to identify the datatype (object), results in

object
object
undefined

Source (Professional JavaScript for Web Developers 3rd Edition):

When defining a variable that is meant to later hold an object, it is advisable to initialize the variable to null as opposed to anything else. That way, you can explicitly check for the value null to determine if the variable has been filled with an object reference at a later time, such as in this example:

if (foo2 != null){
    //do something with foo2
}

The value undefined is a derivative of null, so ECMA-262 defines them to be superficially equal as follows:

console.log(null == undefined); // prints true
console.log(null === undefined);// prints false
Share:
62,246

Related videos on Youtube

KMcA
Author by

KMcA

Updated on July 09, 2022

Comments

  • KMcA
    KMcA almost 2 years

    I have seen different code examples with variables declared and set to undefined and null. Such as:

    var a; // undefined - unintentional value, object of type 'undefined'
    var b = null; // null - deliberate non-value, object of type 'object'
    

    If the code to follow these declarations assigns a value to a or to b, what is the reason for using one type of declaration over another?

  • I Hate Lazy
    I Hate Lazy over 11 years
    Just a note... I think the "[object Null]" result of toString() may have some browser incompatibilities.
  • JR Halchak
    JR Halchak about 7 years
    To the last line, it should be noted that nothing === (triple equals) null outside of null itself (since it's an "object").
  • Álvaro González
    Álvaro González almost 7 years
    Perhaps you could edit the answer and add some reference links and argumentations. Just dropping here "Good practice" is nothing more than an opinion.
  • qrtLs
    qrtLs almost 7 years
    I added the reference book, also "just a book" not norm
  • Yay295
    Yay295 almost 5 years
    If I'm not going to initialize them, why even declare them in the first place? Because you want to set the value with an if..else statement, but need the variable's scope to be outside the if..else? Though in JavaScript var has function scope, so that doesn't really apply in this case.