Javascript: if (c > b > a) - I do not understant... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

24th Jun 2018, 11:23 PM
Jonathan Serradj
Jonathan Serradj - avatar
5 Answers
+ 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
25th Jun 2018, 12:12 AM
Andre Daniel
Andre Daniel - avatar
+ 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.
25th Jun 2018, 5:47 AM
Rowsej
Rowsej - avatar
+ 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 }
25th Jun 2018, 6:09 AM
Haris
Haris - avatar
+ 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.
24th Jun 2018, 11:47 PM
Nsamba Abubaker
Nsamba Abubaker - avatar
+ 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 ^^
25th Jun 2018, 12:02 AM
Hexiimortard
Hexiimortard - avatar