How do you read this JavaScript code? (var1 ? var2:var3)
javascript, operators
Solution
It's known as a ternary (because it has three operands) conditional (because it's an if/else/then) operator.
It is evaluated to a value, so you would usually use it to assign a value, such as:
var result = condition ? value1 : value2;
Which is equivalent to:
var result;
if (condition == true) {
result = value1;
} else {
result = value2;
}
An example:
var message = "Length is " + len + " " + (len==1 ? "foot" : "feet");
Note `?:` is the full operator. It's not a `?` and `:` operator, so `?` by itself is meaningless in Javascript.
Problem
I've seen this format used in JavaScript code, but can't find a good source for the meaning. Edit for a follow-up: Thanks for all the quick answers! I figured it was something like that. Now, for bonus points: can you use (var1 ? var2) to do the same thing as ``` if (var1) { var2 } ``` ?