Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Different return types

Tags:

javascript

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};
    }
 };
like image 751
bsr Avatar asked May 01 '11 15:05

bsr


2 Answers

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 {};
  }
};
like image 27
Tomasz Nurkiewicz Avatar answered Sep 25 '22 06:09

Tomasz Nurkiewicz


I would discourage it. Any code that uses a function that can return different types depending on the context will have to check the returned value.

There are situations where it makes sense, however. Say you have a function that parses a string, for example JSON. In that situation it makes a whole lot of sense to return arrays if the input string is a JSON string representing an array, an object if the input contains an object, a boolean, a number, etc.

In general, do the thing that would cause the least surprise. Your example would surprise me a lot, for example.

like image 75
Theo Avatar answered Sep 24 '22 06:09

Theo