var age = 42; var isAdult = (age < 18) ? "Too young": "Old enough"; document.write(isAdult); | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

var age = 42; var isAdult = (age < 18) ? "Too young": "Old enough"; document.write(isAdult);

How did the compiler determined too young and old enough because is was not assigned to any variable

16th May 2019, 11:36 AM
Henry Monday
Henry Monday - avatar
5 Answers
+ 13
That's the 'ternary operator' at work. x = 1? 2: 3; ... is a shortcut for: if (1) x = 2; else x = 3;
16th May 2019, 11:49 AM
HonFu
HonFu - avatar
+ 5
Ternary operator is used Condition?truestmt:falsestmt In these case condition is if given is less than 18 then true stmt will run other wise false stmt.Age is 42 i.e condition is false so old enough will print
19th May 2019, 8:17 AM
Riya
Riya - avatar
+ 3
That means the question mark (?) Is the one determining the too young and old enough
16th May 2019, 12:24 PM
Henry Monday
Henry Monday - avatar
+ 2
Yeah. The part before the ? is a condition like in an if clause or while loop. Depending on the answer, true or false, it's either the first value or the other.
16th May 2019, 12:33 PM
HonFu
HonFu - avatar
+ 2
The condition (age < 18)? returns a true or false. In this case, the age variable which was assigned 42 is not less than 18, so the condition returns false. Now the string attached to the false is "Old enough". Thus the program will assign "Old enough" to the isAdult variable.
16th May 2019, 12:39 PM
Oluwasayo Akinkunmi
Oluwasayo Akinkunmi - avatar