Using logical test result for default values

It is rather a matter of "experience from the trenches."

Given this javascript snippet

/** * @param [foo] * {Object} an optional object (it can be null, undefined, empty, etc..) * @param [foo.bars] * {Array} an Array that *might* be in the object */ function (foo) { // I want to get the array, or an empty array in any // of the odd cases (foo is null, undefined, or foo.bars is not defined) var bars = []; if (foo && foo.bars) { bars = foo.bars } // .... } 

I am trying to cut it; according to MDN , it should be ok to write:

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

I missed a case (a set of values ​​or another browser), where does this not work? Is there a shorter / cleaner way to do this?

In a more subjective node, do you find this impossible to read?

thanks

+4
source share
2 answers

I don’t like it at all. For an ordinary programmer, he reads as if the resulting value were true, if (foo && foo.bars) evaluates to true, otherwise it would be an empty array.

I would rather see the following:

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

This is the absolutely correct way to do this if you know that foo.bars never defined as a true value that is not an array (for example, foo = {bars: 1}) .

It is unreadable, as most Javascript developments are familiar with how && and || and use them to assign default values ​​all the time.

+4
source

Source: https://habr.com/ru/post/1491893/


All Articles