+ 10
Javascript: if (c > b > a) - I do not understant...
var a = 10; var b = 20; var c = 30; if (c > b > a) { console.log('1'); } else { console.log ('2'); } ------- I do not understand why the result is '2', 30 is greater than 20 and this greater than 10. Is there something that escapes me, can someone solve the doubt?
5 odpowiedzi
+ 18
Jonathan Serradj
First, we need to understand that a comparison between a number and a boolean value will result in internal type conversion of Boolean value to a number (true becomes 1 and false becomes 0)
The expression you have shown is evaluated from left to right. So, first
c > b
is evaluated and the result is true and you are comparing true with a, which is 10. Since true becomes 1 during comparison, 1 > 10 evaluates to false. But if you had said
var a = 0;
then 1 > 0 is true and it would say 1.
See code below:
https://code.sololearn.com/W4I2TJ7QZeVH/?ref=app
+ 7
c > b, so this evaluates to true. In coding, a true is resembled by a 1 and a false by a 0. So, your if statement goes like this:
if(c > b > a)
if(true > a)
if(1 > a)
And, 1 is not greater than 10 (a), so the code in the else section runs.
+ 5
Boolean comparison isn't the same as math comparison.
If you wanted it to be a math comparison it should be written like this:
if (c > b && b > a)
{
statements
}
+ 3
(c>b>a) means c greater b but b greater than a....so the result is 2 because c I greater than b and b is greater than a.....It would be 1 if b was greater than c or b was less than a.
hope that clears your doubt.
+ 3
Hi there, like Nsamba said it’s the placement of the (c >b > a)
If you put it as:
var a = 10;
var b = 20;
var c = 30;
if (c > b && b > a) {
console.log('1');
} else {
console.log('2');
}
The output would be 1! Thank you for reading ^^