Skip to main content

String Concatenation vs Conditional Operator in Java and JavaScript

· 2 min read

Java:

System.out.println("client " + authorized ? "authorized" : "unauthorized");

JavaScript:

alert('client ' + authorized ? 'authorized' : 'unauthorized');

(Let's assume that the authorized is a parameter variable)

In Java, if you write code like this, you definitely get a compile time error, since String concatenation gets higher precedence than conditional operator whereas in JavaScript, you don't get any error although String concatenation has higher precedence just like Java.

Reason for that is unlike Java which allows only true or false (or boxed Boolean) for conditional expression, in JavaScript, there are several cases that make conditional expression working and make the evaluation result of it false (false, undefined, 0, Number.NaN, "" (empty String), etc.) or true (cases other than the ones making it false). So if you have some value other than those and test it, the result is true.

e.g.) some cases making the evaluation of conditional expression false.

if (0) {
// false so never come here.
}

if (undefined) {
// false so never come here.
}

if (Number.NaN) {
// false so never come here.
}

if (false) {
// false so never come here.
}

if ("") {
// false so never come here.
}

e.g.) some cases making the evaluation of conditional expression true.

if (1) {
// true!
}

if ("some value") {
// true!
}

if (true) {
// of course true!
}

if ({}) {
// true!
}


if ({"someName":"someValue"}) {
// true!
}


if ([]) {
// true!
}


if ([1,2,3,]) {
// true!
}

So this code

alert('client ' + authorized ? 'authorized' : 'unauthorized');

will eventually become like

if authorized is true,

alert('client true' ? 'authorized' : 'unauthorized');

then

alert('authorized');

if authorized is false,

alert('client false' ? 'authorized' : 'unauthorized');

then

alert('authorized');

if the caller of the function didn't send the authorized.

alert('client undefined' ? 'authorized' : 'unauthorized');

then

alert('authorized');

So if you want to get the result you want, the conditional operator part should be wrapped in parentheses.

alert('client ' + (authorized ? 'authorized' : 'unauthorized'));

In Java, you must!

System.out.println("client " + (authorized ? "authorized" : "unauthorized"));