You are correct. JavaScript variables are automatically initialized to undefined. So given that void 0 returns undefined, these two statements do exactly the same thing:
var cb;
or
var cb = void 0;
Well... Not quite the same thing. Here's a case where it would make a difference:
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!
}
So one might use var cb = void 0; in the second part of that function just to make sure that cb wasn't accidentally assigned a value above. OTOH, many IDEs will give you a warning on that second var declaration, so you would be ignoring that warning at your own risk.
In any case, this kind of repeated variable declaration is often a sign of a badly written function, one that does too much and ought to be broken up into smaller functions.
A couple of other possible reasons I can think of for doing the var cb = void 0;:
- To make it explicit that the variable is being set to
undefined (assuming that the reader knows that void 0 returns undefined!). But this isn't necessary, since it is well defined that JavaScript initializes variables to undefined automatically
- Having cut their teeth on a language like C where a newly declared variable is initialized to random garbage, they don't trust that the right thing will happen if they leave out the assignment. This isn't necessary either, since JavaScript is not C.