Conditional Operator (ternary)
Open the project folder
In our starter files, open the index.html page from this lessons folder:
06.Loops-and-conditionals > 07.Conditional-operator
What is a conditional operator?
As an alternative to the if...else statements we have looked at, JavaScript also has a conditional operator. Often referred to as the ternary operator, since it is made up of three parts.
Since it works just like if...else, the main reasons why it is used is to offer a simple, single line alternative.
Conditional operator syntax
Looking at this user object, we may want to check the user's age before allowing them into a venue:
let user = {name: 'Bob', age: 17};
The conditional operator can help with this, and it is set out like a question:
let user = {name: 'Bob', age: 17};
user.age >= 18 ?
Here we are asking is the user's age greater or equal to 18, using the question mark. The conditional operator is made up of three parts, this question is the first part. The second and third parts are what to do if the answer is true or false.
If true, we can do anything, but this simple example just has the text of enter:
let user = {name: 'Bob', age: 17};
user.age >= 18 ? 'enter'
If it is false, which is correct for this example, the code after a colon will run instead:
let user = { name: "Bob", age: 17 };
user.age >= 18 ? "enter" : "sorry, not today…";
Converting an if...else
We have the following to get us going in the index.html:
<body>
  <p id="edit"></p>
  <script>
    let user = { name: 'Chris', role: 'admin' };
    let canEdit = false;
    if (user.role === 'admin') {
      canEdit = true;
    } else {
      canEdit = false;
    }
    document.querySelector('#edit').innerText = canEdit;
  </script>
</body>
Here we have a simple example of how we can use an if...else statement to check if the user is an admin who can edit something on our site.
Using this example, we can re-write this using the conditional operator to place this onto one single line:
  let user = { name: 'Chris', role: 'admin' };
  let canEdit = false;
  user.role === 'admin' ? canEdit = true : canEdit = false;
  document.querySelector('#edit').innerText = canEdit;
We can shorten this demo even further by instead assigning the result directly to the canEdit variable:
let user = { name: "Chris", role: "admins" };
let canEdit = user.role === "admin" ? true : false;
Leaving a much shorter example. Both the conditional operator and the if...else version are perfectly valid to use. The conditional (ternary) is usually shorter and placed onto a single line, some argue that an if...else is clearer and more readable. In the end the choice is yours which one you prefer to use.