I'm working on nodejs (although my question is valid for javascript in general) and I stumbled upon something 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 true, the final result will be the first value that appears after that 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 made this little code snippet:
var isValid = false;
var message;
if(isValid){
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, when using the ternary operator it ignored for some reason that my variable isValid
was in false
, does anyone have an idea why this is happening? And if it was an expected behavior (which I doubt) I'd like to know why.
You must use parentheses:
The operator
+
takes precedence. What the compiler understands is the following:So print:
Since
"Ésta condición " + isValid
it evaluates totrue
.By the way, this order of precedence applies to most languages (I honestly don't know if there are any that are backwards), including JavaScript.
This is the full JavaScript operator precedence table (see on MDN ).
The result is not exactly what you say. The actual result is:
This is because the + operator takes precedence over ?. What you do is first concatenate
"Ésta condición " + isValid
and then check the result of that concatenation for the ternary operator condition. Since in javascript a non-empty string is true, it says "is valid".Two things happen:
The first is that as they say in the previous comments, the operator
+
has more priority in that expression, so the first thing it does is add and then it applies the ternary operator.JavaScript interprets that the sum of a non-empty string
false
is the string itself.In my opinion, Javascript has a problem with precedence and its parser itself... because it tries to make everything compile and if something doesn't fit, it discards it.
Your code translates as:
To solve this problem in an elegant way you can use
string templates
the following:I hope someone finds it helpful.