+ 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
5 ответов
+ 13
That's the 'ternary operator' at work.
x = 1? 2: 3;
... is a shortcut for:
if (1) x = 2;
else x = 3;
+ 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
+ 3
That means the question mark (?) Is the one determining the too young and old enough
+ 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.
+ 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.