bsr bsr - 4 months ago 14
Javascript Question

Javascript: Different return types

I saw I could return different types from the same function in JavaScript. Is this practice idiomatic or should it be discouraged?

For example:

somefn = function(e) {
switch (e.type)
{
case 'mousedown':
return false;
case 'mousemove':
return {x:10, y:20};
}
};

Answer

Please note that not only your function returns different types, but might even not return anything:

somefn({type: 'foo'});  //undefined

Although inconsistent return behavior described above is discouraged, returning different object types is common, although I can't say if it is idiomatic.

For the sake of readability and maintainability I wouldn't recommend returning completely different objects (like boolean and object literal in your example), but returning object literals with just slightly or even completely different properties is pretty common:

somefn = function(e) {

  switch (e.type) 
  {
    case 'mousedown':
      return {x:10, y:20, down: false};
    case 'mousemove':
      return {x:10, y:20};
    default:
      return {};
  }
};
Comments