Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate `?:` Conditional Strings in JavaScript

Tags:

javascript

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.

like image 421
Jonathan Wood Avatar asked Dec 11 '22 06:12

Jonathan Wood


2 Answers

Wrap the second ternary in parentheses and it works:

(((i % 12) == 0) ? '12' : (i % 12)) + ((i < 12) ? 'AM' : 'PM')
like image 115
CoderDre Avatar answered Dec 25 '22 13:12

CoderDre


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')
like image 30
Ahmad Mageed Avatar answered Dec 25 '22 12:12

Ahmad Mageed