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'
?
If the input String is not null , the first ternary operator returns the value of the second ternary operator. The second ternary operator checks if the input String is equal to the empty String. If it is, the second ternary operator returns 0 immediately.
In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "snow" and "ball" is "snowball".
The & operator is recommended for string concatenation because it is defined exclusively for strings and reduces your chances of generating an unintended conversion.
In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.
Both of the submitted answers are correct, you need to add parentheses. I figured I'd talk briefly about why.
alert("test: "+(1==2)?'hello':'world');
When the parser encounters a statement, it will begin recursively breaking it down into smaller and smaller chunks.
In this case, the first thing it encounters is a function: alert
. Immediately the parser will look at alert
's arguments, and begin parsing each of them individually. This function only has one argument, "test: "+(1==2)?'hello':'world'
, making it an easy first step.
At this level we can break our statement down into a series of binary comparisons. Javascript parsers form binary pairs from left-to-right (when order of operation values are the same). Our potential candidates are "test: "
, (1==2)
, 'hello'
and 'world'
with operators +
, ?
and :
. The parser will first attempt to add "test: "
and (1==2)
. To do this it must first evaluate the statement (1==2)
(which evaluates to false
). The +
operator causes concatenation with strings and forces all primitive variables to attempt to represent themselves as strings as well. false
evaluates as the string "false"
creating the statement "test: false"
.
The parser is now ready to evaluate the first part of the ternary: "test: false"?
. In Javascript, all non-empty strings evaluate to true
, passing the ternary operator's test and picking the first option "hello"
.
By throwing a few extra parenthesis into the original statement:
alert("test: " + ((1 == 2) ? 'hello' : 'world'));
We tell the parser that we want to evaluate the ternary operator BEFORE concatenation.
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'
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