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

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]"

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)