This is a one-line shorthand for an if-else statement. It's called the conditional operator.1
Here is an example of code that could be shortened with the conditional operator:
var userType;
if (userIsYoungerThan18) {
userType = "Minor";
} else {
userType = "Adult";
}
if (userIsYoungerThan21) {
serveDrink("Grape Juice");
} else {
serveDrink("Wine");
}
This can be shortened with the ?: like so:
var userType = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");
Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:
userIsYoungerThan21 ? serveGrapeJuice() : serveWine();
They can even be chained:
serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');
Be careful, though, or you will end up with convoluted code like this:
var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;
1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.
Answer from Peter Olson on Stack OverflowQuestion on if/when to use Ternary Operators?
Use the Conditional (Ternary) Operator Why?
What are pros/cons of ternary conditional operators? - Programming Language Design and Implementation Stack Exchange
[AskJS] Nullish Check in conditional
Videos
This is a one-line shorthand for an if-else statement. It's called the conditional operator.1
Here is an example of code that could be shortened with the conditional operator:
var userType;
if (userIsYoungerThan18) {
userType = "Minor";
} else {
userType = "Adult";
}
if (userIsYoungerThan21) {
serveDrink("Grape Juice");
} else {
serveDrink("Wine");
}
This can be shortened with the ?: like so:
var userType = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");
Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:
userIsYoungerThan21 ? serveGrapeJuice() : serveWine();
They can even be chained:
serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');
Be careful, though, or you will end up with convoluted code like this:
var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;
1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.
I want to add some to the given answers.
In case you encounter (or want to use) a ternary in a situation like 'display a variable if it's set, else...', you can make it even shorter, without a ternary.
Instead of:
var welcomeMessage = 'Hello ' + (username ? username : 'guest');
You can use:
var welcomeMessage = 'Hello ' + (username || 'guest');
This is Javascripts equivallent of PHP's shorthand ternary operator ?:
Or even:
var welcomeMessage = 'Hello ' + (username || something || maybethis || 'guest');
It evaluates the variable, and if it's false or unset, it goes on to the next.
So i am completly new to programming and learning thru codecademy.
I just got thru all the lessons about if else statements and when/how to use them but in their next lession they talk about Ternary Operator basically being a "shot handed" version of wirting an if else statement (if I am understanding that correctly) if I am understanding it correctly then my question is, is one more "professional" then the other or is it just based on what your coding or what lets say your boss is asking you to code
The other reason I ask is I want to devlope good habits now vs later down the road so using the example below is it I guess from a "real world" working senario is it better to use one over the other
For example; I know this is a very genaric and basic example but
let nightTime = true
if (nighTime) {
console.log('Nightime');
} else {
console.log('Daytime')
}vs
nightTime
? console.log('Nighttime')
: console.log('Daytime');Pro: Readability
While plenty of people talk about the readability problems with misused ternary operators, there are also situations where using a full if/else would be annoyingly bulky, spreading a simple statement across five lines, and significantly reducing readability. Here are some sample statements pulled from a project I'm working on:
bg_2d.fillStyle = is_in_bounds(x, y) ? grid_colors[x][y] : "#ffffff";
const diagonal_slowdown = is_diagonal() ? Math.SQRT2 : 1;
const color = (team == "red") ? "#ff0000" : "#0000ff";
When you have a simple situation where you have two things to pick from based on a condition, which happens all the time, ternary is perfect. Having a short syntax for ternary massively improves readability in these situations.
Pros:
It's an expression, and in languages with distinction between expressions and statements it's crucial to have a selection operator available as an expression. Ternary operator is not necessarily the best syntax though, as the other answers highlighted how convoluted it can become with very little effort. A good alternative is an if-then-else available as an expression and not just statement.
Cons:
It's introducing control flow into expressions, just like logic operators in many languages. When side effects are possible, it's making expressions less visually obvious to follow.
The C-style syntax of C?T:F often leads to convoluted and error-prone code.