1

I'm fairly new to javascript and I saw this issue which I couldn't make any sense of,

Here's the code and inspector output from Chrome,

> test?'test':'ok'
"ok"
> [test?'test':'ok']
["ok"]
> ['ok' + test?'test':'ok']
["test"]

What is going on with this array? All I want is to create an array ['browser' + isIE? 'IE' : 'UNKNOWN'].

I could do it with [isIE? 'browser: IE' : 'browser: UNKNOWN'] which works. But I don't understand what is wrong with above syntax?

4
  • Syntax error. Please verify. Commented Dec 18, 2012 at 17:05
  • ['browser' + isIE? 'IE' + 'UNKNOWN'] doesn't look right. Should be ['browser' + isIE ? 'IE' : 'UNKNOWN'] (note the colon :) Commented Dec 18, 2012 at 17:06
  • Well, what's the value of test? Commented Dec 18, 2012 at 17:07
  • Thanks rae1n. My mistake fixed the syntax error with question. Commented Dec 18, 2012 at 17:13

2 Answers 2

5

You can rewrite [isIE? 'browser: IE' : 'browser: UNKNOWN'] to:

["browser: " + (isIE ? 'IE' : 'UNKNOWN') ]

I would recommend to always use brackets with the conditional operator.

A common pitfall is: bool ? "a" : "b" + "c" will give "a" or "bc", but not the intended "ac".

(bool ? "a" : "b") + "c" is the intended functionality.

Another pitfall:

'ok' + test?'test':'ok' gives "test" or "ok" but never "oktest" or "okok". This is because 'ok' + test is treated as a boolean (which will always be true I think?).

'ok' + (test ? 'test' : 'ok') is the intended functionality.

Sign up to request clarification or add additional context in comments.

1 Comment

And you can overcome this issue by parenthesis like: (bool ? "a" : "b") + "c" This way you will get either 'ac' or 'bc'.
2

This is how the expression is evaluated:

('ok' + test) ? 'test' : 'ok';

Evaluate the concatenation of 'ok' and test, return 'test' if truthy, 'ok' otherwise.

What you want is:

'ok' + (test ? 'test' : 'ok');

Concatenate 'ok' with the result of ternary expression, which is 'test' if test is truthy, 'ok' otherwise

Update

Concrete example. This will return what you want.

'browser: ' + (isIE? 'IE' : 'UNKNOWN')

I wasn't sure whether you wrapped the expression in square brackets to denote an array or not, but I've left them off here ;-)

1 Comment

Awesome! this was the issue with expression. Thanks Jack you rock.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.