4️⃣

3.4 Ternary Operator

3.4 Ternary Operator

What Is a "Ternary Operator"?

JavaScript has this special operator (well, actually it's pretty common in programming languages) called the ternary operator. It uses : and ? in its structure, and assigns a value to a variable based on some condition. This is like a shorter form of a if-else statement.

Why Use a Ternary Operator?

It's simply syntax sugar (something that makes your code more pretty). You can replace a ternary operator with an if-else statement, but using this makes your code shorter and flexes your JavaScript knowledge.

Basic Structure

Here is the basic structure:
<condition> ? <value1> : <value2>;
  1. Ternary operator starts with conditional expression followed by the ? operator.
  1. The second part (after ? and before : operator) will be placed into the variable if the condition is true.
  1. IF the condition is false, then the third part (after :) will be placed into the variable.

Practice

You can add practice problems here if you want. Follow the format below.
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.