Reputation: 310
Would someone mind converting this line of ternary code to if
/then
statements. I understand ternary, but am not able to get syntax errors to go away when I convert to if
/then
. This is the only line of my homework I had to borrow and I'd like to make it into if
/then
so that I can comment on it and understand it better myself.
Original:
return n == null || isNaN(n) ? 0 : n;
My attempt:
return n == null || if(isNaN(n)){return 0;}else{return n;}
Upvotes: 1
Views: 659
Reputation: 23500
The problem is that return must be the first statement on any line it appears (as per the ECMA specs).
The code is easier to translate if you first add parentheses ( n == null || (isNaN(n) ? 0 : n)
gives different results and is not equivalent to javascript's default parsing of un-parenthesesed code)
return (n == null || isNaN(n)) ? 0 : n;
which is equivalent to
if (n == null || isNaN(n)) {
return 0;
} else {
return n;
}
Upvotes: 0
Reputation: 664405
You will need to apply some grammatics here:
The other four answers present the correct source code, I don't want to repeat it.
Upvotes: 0
Reputation: 150020
This is what I think it is doing:
if (n == null || isNan(n))
return 0;
else
return n;
The ||
operator has higher precedence than the ?
operator.
Upvotes: 0
Reputation: 141839
You have to move the return
and have a separate one for the if and the else:
if(n == null || isNaN(n)){
return 0;
}else{
return n;
}
Upvotes: 0