The Conditional Operator
Often, the page should show one of two things, depending on the data: “open” or “closed”, a price or “sold out”. For that, JavaScript has the conditional operator, written with a question mark and a colon:
condition ? valueIfTrue : valueIfFalseJavaScript checks the condition. When it's true, the whole expression gives the value after ?; when it's false, the value after :. In a template:
<script setup>
const open = true;
const name = "Carrot Cake";
const vegan = true;
</script>
<template>
<p>We're {{ open ? "open" : "closed" }}.</p>
<p>{{ name }}{{ vegan ? " (vegan)" : "" }}</p>
</template>The page shows We're open. and Carrot Cake (vegan). With const open = false;, it shows We're closed., and with const vegan = false;, just Carrot Cake. The empty text "" shows nothing, so the second paragraph adds (vegan) only when vegan is true.
The condition can be anything you'd write in an if: price > 3, count === 1, open && !full. And the operator works anywhere in JavaScript, not only in templates. It's like a short if/else that gives a value:
const word = cups === 1 ? "cup" : "cups";Why not an if right in the braces? Because {{ }} takes only expressions, code that gives a value. if, for and const are statements: they do something, but they don't give a value. With {{ if (open) { "open" } }}, the app doesn't run, and the message under the preview says Error parsing JavaScript expression: Unexpected token. To show a whole element only when a condition is true, templates have v-if, which you'll learn in the lesson Conditions and Lists.
Typical mistakes:
- Without the part after
:, as in{{ open ? "open" }}, the app doesn't run: the conditional operator always needs both values. When one of them should be nothing, use"".
Instructions
- 1
The page shows
Open: true, which isn't very friendly. Change the paragraph so that it showsWe're open!whenopenis true, andSorry, we're closed.when it's false. Click the button to try both. - 2
Make the button say what it will do:
Close the caféwhile the café is open, andOpen the caféwhile it's closed.