4

I'm trying to understand the libraries used in this article and elsewhere, and there's some pretty mind bending stuff in there, among which is the line

var cb = void 0;

I've learned that void 0 returns undefined, but isn't a var undefined by default? Why not just use the following instead?

var cb;
Alex
  • 1,061
  • 2
  • 11
  • 19
  • void 0 is actually shorter than undefined, hence it reduces the code length. – briosheje May 11 '17 at 08:55
  • 1
    Note that I am not asking what void 0 does, but why it is made explicit in this case. – Alex May 11 '17 at 09:48
  • 1
    I am starting to think that this code might be the output of a code generator or transpiler, which would satisfy me as to why it may not be idiomatic Javascript. – Alex May 11 '17 at 09:50
  • yes, sorry, what I meant is that you usually find void 0 instead of undefined because, since it's shorter, transpilers takes advantages over that to reduce the length of the transpiled code. – briosheje May 11 '17 at 13:11

2 Answers2

4

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;:

  1. 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
  2. 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.
Michael Geary
  • 28,450
  • 9
  • 65
  • 75
0

Or maybe to make sure cb is initialised with undefined and nothing else (undefined was writable in ES3).