In JavaScript, there is generally no good reason to initialize variables to null
.
In languages like C, variables should always be initialized before use because there is no guarantee as to the value of an uninitialized variable – it could be 0, 1, 2, or 283942, or anything. However, JavaScript has no such problem. In JavaScript, variables that have been declared but not initialized will always have the value undefined
.
undefined
is it's own type in JavaScript. When cast to a boolean, it becomes false
.
undefined == null
returns true
, but undefined === null
returns false
.
Semantically, undefined
means that a value has not been set, whereas null
means that there is no value, but we might expect one. However, there is no hard rule for this, as you can always assign the value undefined
to a variable manually – I wouldn't recommend this.
In general, setting uninitialized variables to null
would be a waste of time.