Why is the ternary operator not working in javascript?


I am working on nodejs (although my question is valid for javascript in general) and I came across something that I don't understand.

It is related to the ternary operator which, as I understand it , works like this:

var numero = 5;
var positivo = numero >= 0 ? true : false; 

If the condition ( numero >=0 ) is fulfilled, the final result will be the first value that appears after said condition, in this case true . Otherwise, the final result will be the second value, in this case false .

So when printing:

console.log(positivo); //imprime true

If I change the variable numero , I can get a false value:

var numero = -1;
var positivo = numero >= 0 ? true : false; 
console.log(positivo); //imprime false

So far so good, but trying to isolate my problem I did this little code snippet:

var isValid = false;
var message;

  message = 'es válida';
}else {
  message = 'no es válida';

console.log("Ésta condición " + message);
console.log("Ésta condición " + isValid ? 'es válida' : 'no es válida');

According to my logic, since in my code the variable isValid is false, both messages should print:

Ésta condición no es válida

However when I run my program the result is this:

Ésta condición no es válida
es válida

As you can see, using the ternary operator has ignored for some reason that my isValid variable was set to false , does anyone have any idea why this happens? And if it was an expected behavior (which I doubt) I'd like to know why.


You must use parentheses:

console.log("Ésta condición " + (isValid ? 'es válida' : 'no es válida'));

The + operator takes precedence. What the compiler understands is the following:

console.log(("Ésta condición " + isValid) ? 'es válida' : 'no es válida');

Then print:

es valida

Since "Ésta condición " + isValid evaluates to true .

By the way, this order of precedence applies to most languages ​​(honestly, I don't know if there are any that are the other way around), including JavaScript.

This is the complete table of precedence of operators in JavaScript (see in MDN ).

Scroll to Top