3

I often read through source code as a good resource for learning programming. I was looking at Backbone.Model's fetch() method and had this question I was hoping someone could shed some light on.

Here is the fetch() method:

// ---------------------------------------------------------------------
// Fetch the model from the server. If the server's representation of the
// model differs from its current attributes, they will be overriden,
// triggering a `"change"` event.
fetch: function(options) {
  options = options ? _.clone(options) : {};
  if (options.parse === void 0) options.parse = true;
  var success = options.success;
  options.success = function(model, resp, options) {
    if (!model.set(model.parse(resp, options), options)) return false;
    if (success) success(model, resp, options);
  };
  return this.sync('read', this, options);
}

My question is, what is the point of the if condition if (options.parse === void 0)...? void 0 simply evaluates to 'undefined', so is this a shorthand for testing if the property is not defined? And if so, does it have any advantages over the standard (typeof options.parse === 'undefined') statement, which I find more semantic and readable?

T Nguyen
  • 3,309
  • 2
  • 31
  • 48
  • 7
    see http://stackoverflow.com/q/4806286/989121. Probably `typeof` looked too verbose to them. – georg Feb 20 '14 at 14:53
  • Cool, thanks for that. So it sounds like it is a slightly stricter form of `undefined` since `undefined` itself can be overwritten in most legacy versions of Javascript. – T Nguyen Feb 20 '14 at 14:57
  • Even if undefined is overwritten, typeof an undefined variable would still return 'undefined', or am I missing something? – kinakuta Feb 20 '14 at 19:18
  • @kinakuta: As far as I understand, if you assign `undefined = 'foobar'` then the type of it will actually become 'string'. Then, if you test the typeof a variable that hasn't been defined, it will evaluate as 'string'. However, I'm having trouble checking this because it's really hard to run an old version of ECMAScript which still allows overwriting the value of `undefined` :) http://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/ – T Nguyen Feb 21 '14 at 14:48
  • You can run IE in IE8 compatibility mode to test this. If you assign undefined another value, you'll still get 'undefined' when testing the typeof an undefined variable. – kinakuta Feb 21 '14 at 19:46

1 Answers1

0

Aside from code size and performance, there's another reason to use void 0. Some browsers allow undefined to be assigned other values. This can lead to code that's broken in a browser dependent way.

See: JavaScript `undefined` vs `void 0`

Community
  • 1
  • 1
Mark Wilbur
  • 2,809
  • 2
  • 23
  • 22