Question

Problem: The function is not returning the value that is expected (3).

The following code does not evaluate as expected returning 1. I've found that this is due to the usage of the ternary operator. What about the ternary causes the return value to be unexpected? Is it precedence? The ternary operator is right associative according to the mdn specifications.

function foo()
{
    var x = 1;
    var flag = true;

    function bar(a,b)
    {
        return a + b;
    }

    var y = bar(2,2) - (flag) ? x : 0;

    return y;   
}    
alert(foo());

Note that if I modify the line:

var y = bar(2,2) - (flag) ? x : 0;

to

var y = bar(2,2) - ((flag) ? x : 0);

The above code will act as expected returning 3.

Also note that if I replace the function with any type of float

var y = 3 - (flag) ? x : 0;

The same unexpected return value is evaluated to 1.

Was it helpful?

Solution 2

You guessed correctly: It is precendence. The operator - is evaluated before the ternary operator.

var y = bar(2,2) - (flag) ? x : 0;

is evaluated as

var y = (bar(2,2) - (flag)) ? x : 0;

You can see the operator precedence here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Note that the "conditional" (ternary) operator is way down on the list.

OTHER TIPS

This issue is that you're assuming space or parenthesis delimit automatically.

var y= bar(2,2) - (flag) ? x : 0;

is the same as

var y= (bar(2,2) - (flag)) ? x : 0;

and is not the same as

var y= bar(2,2) - ((flag) ? x : 0);

That's because when you leave the code like this:

var y = bar(2,2) - (flag) ? x : 0;

It evaluates to this:

var y = (bar(2,2) - (flag)) ? x : 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top