user7066345 user7066345 - 14 days ago 5
Javascript Question

does javascript have weird behavior returning a function value from a ternary statement?

Does javascript have weird behavior returning a value from a ternary statement? Here's a function I wrote for an app which returns a value from a ternary statement:

function getFlowAmount(fromRegionName, toRegionName)
{
return
_reportPeriodId === 1 ?
mapData[toRegionName + 'Region']['NetFlow' + fromRegionName ] :
mapData[toRegionName + 'Region']['NetFlowChange' + fromRegionName];
}


The function above was returning undefined even though a dev tools watch showed that a value should be returned so I rewrote the function in a more modular and verbose way like this:

function getFlowAmount(fromRegionName, toRegionName)
{
var flowAmount = 0;
if(_reportPeriodId === 1) flowAmount = mapData[toRegionName + 'Region']['NetFlow' + fromRegionName ];
else flowAmount = mapData[toRegionName + 'Region']['NetFlowChange' + fromRegionName];
return flowAmount;
}


When I rewrote the javascript function as shown above, the function started returning the expected value. So does javascript have weird behavior returning a function value from a ternary statement? Or did I make some type of syntax or logic error in my original function above?

Answer

It's not super intuitive, but this has nothing to do with the ternary operation. This is all about automatic semicolon insertion.

While an expression itself can span multiple lines, in JavaScript there can not be a new line between the return statement and the start of the expression. So this:

return 
    _reportPeriodId === 1 ? 
    mapData[toRegionName + 'Region']['NetFlow' + fromRegionName ] : 
    mapData[toRegionName + 'Region']['NetFlowChange' + fromRegionName];

becomes this:

return;
    _reportPeriodId === 1 ? 
    mapData[toRegionName + 'Region']['NetFlow' + fromRegionName ] : 
    mapData[toRegionName + 'Region']['NetFlowChange' + fromRegionName];

And the ternary operation is never evaluated in the first place.

To correct it, simply begin the operation on the same line:

return _reportPeriodId === 1 ? 
    mapData[toRegionName + 'Region']['NetFlow' + fromRegionName ] : 
    mapData[toRegionName + 'Region']['NetFlowChange' + fromRegionName];
Comments