+ 3
What does The question Mark means?
var age = 42; var isAdult = (age < 18) ? "Too young": "Old enough"; document.write(isAdult);
7 Antworten
+ 9
If age < 42 then isAdult = "too young" else isAdult = "old enough"
+ 5
(condition) ? (result if true) : ( result if false)
so your example is equivalent to:
if (age < 18)
isAdult ="Too young";
else
isAdult = "Old enough";
+ 3
? tells the compiler that the "Too young":"Old enough" are used as the answer of the boolean operation before
+ 2
this one is called conditional operator (or sometimes just ternary operator)
let me explain it this way
the value on the left of the question mark picks which of the other two values will come out.
when it is true the middle one value is chosen, and
when it is false, the value on the right comes out
for example
console.log(true ? 1 : 2);
in this case 1 comes out...
console.log(false ? 1 : 2);
in this case 2 comes out ...
+ 1
?
+ 1
thx
+ 1
That is called `Ternary Operator`. It's like the; If else condition that was written on a single line instead.