Shorthand If
Learn all about Shorthand If in this comprehensive tutorial.
- •If you have only one statement to execute, you can put it on the same line as the if statement.
- •If you have one statement for if and one for else, you can put them on the same line using a conditional expression:
- •You can also use a one-line if/else to choose a value and assign it to a variable:
- •You can chain conditional expressions, but keep it short so it stays readable:
- •Ternary operators are particularly useful for simple assignments and return statements.
- •Shorthand if statements and ternary operators should be used when:
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Short Hand If ... Else
If you have one statement for if and one for else, you can put them on the same line using a conditional expression:
Assign a Value With If ... Else
You can also use a one-line if/else to choose a value and assign it to a variable:
The syntax follows this pattern:
Multiple Conditions on One Line
You can chain conditional expressions, but keep it short so it stays readable:
Practical Examples
Ternary operators are particularly useful for simple assignments and return statements.
When to Use Shorthand If
Shorthand if statements and ternary operators should be used when:
- The condition and actions are simple
- It improves code readability
- You want to make a quick assignment based on a condition
Module quiz
2 questionsWhich of the following is true about Shorthand If?
What is the most common pitfall when working with Shorthand If?
Answer all questions to submit.