5

Its being annoying

Following code :

var arrays = [1,2,3];
alert('Array has ' + (arrays.length > 0) ? 'multiple':'single' + ' value');

alerts as the multiple where string is not concatenated with the ternary result.

But this code :

var arrays = [1,2,3];
alert('Array has ' + ((arrays.length > 0) ? 'multiple':'single') + ' value');

alerts as the Array has multiple value where string is concatenated with the ternary result.

My question is :

  1. Why the first code is not concatenated with string.
  2. Is there any syntax error in first code, if so why it doesnt throw an error.
0

2 Answers 2

14

Your first example is parsed this way

alert(('Array has ' + (arrays.length > 0)) ? 'multiple':('single' + ' value'));

given the operator precedence of + is much higher than that of ?:.

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

1 Comment

Really so awesome answer.
5

Both snippets are syntactically correct, but they differ because of operator precedence. The ternary operator has lower precedence than +.

In the first snippet:

var arrays = [1,2,3];
alert('Array has ' + (arrays.length > 0) ? 'multiple':'single' + ' value');

Javascript evaluates the first part 'Array has ' + (arrays.length > 0), which gives the string 'Array has true'. For conditional purposes, the nonempty string is the same as true (usually called a truthy value). Because the first operand in the ternary operator is truthy, the value of the whole expression will be the value of the expression 'multiple', that's between the ? and the :.

When you add the parameters in the second snippet, you make the ternary operator take only (arrays.length > 0) as its condition. That's why the code works as expected.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.