A valid point has been made here. JavaScript variables are indeed automatically initialized to undefined
. Therefore, the statements var cb;
and var cb = void 0;
essentially achieve the same result:
var cb;
or
var cb = void 0;
However, there is a subtle distinction. Consider this scenario where it does matter:
function foo() {
var cb;
// some stuff
cb = 42;
// a lot more stuff, lots of lines of code here!
// ... really a lot of code here ...
// ... so much code that I forgot the first part of the function...
var cb; // I forgot that I already defined cb above!
alert( cb ); // Do I expect undefined? I will be surprised!
}
In such cases, using var cb = void 0;
in the second instance within the function can help ensure that unintentional re-assignments are avoided. Nevertheless, many Integrated Development Environments (IDEs) would flag this as a warning, hence ignoring this warning could pose its own risks.
Furthermore, repeating variable declarations like this often indicate poorly structured functions that should ideally be subdivided into smaller functions for better readability and maintainability.
There are a few reasons why one might choose to use var cb = void 0;
:
- To explicitly show that the variable is being set to
undefined
(assuming the reader understands that void 0
yields undefined
). However, given that JavaScript inherently initializes variables to undefined
, this explicit assignment may not be essential.
- Due to prior experience with languages like C where new variables initialize to random values, there may be a lack of confidence that omitting an assignment would yield the desired outcome. Nonetheless, it's important to note that JavaScript behaves differently from C in this aspect.