javascript - Using result of logical tests for default values -


this more of "experience trenches" question.

given piece of javascript

/**  * @param [foo]   *         {object} optional object (it can null, undefined, empty, etc..)  * @param [foo.bars]  *         {array} array *might* in object  */ function (foo) {   // want array, or empty array in    // of odd cases (foo null, undefined, or foo.bars not defined)   var bars = [];   if (foo && foo.bars) {      bars = foo.bars   }   // .... } 

i'm trying shorten ; according mdn should ok write :

function (foo) {   var bars = (foo && foo.bars) || [];   // ... } 

am missing case (set of value, or other browser) not work ? there shorter / cleaner way ?

on more subjective node, consider unreadable ?

thanks

i don't @ all. conventional programmer, reads if resulting value true if (foo && foo.bars) evaluates true, otherwise empty array.

i prefer see following:

var bars = (foo && foo.bars) ? foo.bars : []; 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -