I set a break point in my JavaScript and I typed the following expressions into the Chrome browser Console window:
Typed:
(((i % 12) == 0) ? '12' : (i % 12))
Result:
9
Typed:
' ' + (i < 12) ? 'AM' : 'PM'
Result:
"AM"
Typed:
(((i % 12) == 0) ? '12' : (i % 12)) + ' ' + (i < 12) ? 'AM' : 'PM'
Result:
"AM"
My expectation was that the last result would be "9AM", which is what I want. That's the result I get if I type 9 + "AM"
. Why does it just give me "AM"?
Am I making a stupid mistake here somewhere, or is there something here that extends beyond my limited understanding of the inner workings of JavaScript? i
is just a for
loop variable.
Wrap the second ternary in parentheses and it works:
(((i % 12) == 0) ? '12' : (i % 12)) + ((i < 12) ? 'AM' : 'PM')
The issue is the part you think you're concatenating is in fact acting as part of the latter ternary condition. Specifically, taking the latter portion of the first ternary, your expression is equivalent to
(i % 12) + ' ' + (i < 12) ? 'AM' : 'PM'`
The condition portion, (i % 12) + ' ' + (i < 12)
evaluates to "9 true", which is a truthy result. Since it's truthy, the result returned is "AM"; the "9" is evaluated as part of the condition rather than being concatenated as you intended.
Thus, the solution is to group the last bit to correctly isolate the ternary result:
((i < 12) ? 'AM' : 'PM')
The updated code becomes:
(i % 12 == 0 ? '12' : i % 12) + ' ' + (i < 12 ? 'AM' : 'PM')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With