user1091856 user1091856 - 3 months ago 18
Javascript Question

Using the ternary operator with string concatenation

alert("test: "+(1==2)?'hello':'world');


This should show me
'world'
on the screen since 1 is not equal to 2.

How come it alerts
'hello'
?

Answer

Try wrapping your parens around the operation

alert("test: "+ (1 == 2 ? 'hello' : 'world'));

demo: http://jsfiddle.net/hunter/K3PKx/


what this is doing:

alert("test: "+(1==2)?'hello':'world');

is evaluating "test: " + (1==2) as true which outputs 'hello'

Comments