Learning Goals
At the end of this Tutorial, you will be able to:
- Write basic statements that test Booleans, strings and numbers with the ternary operator.
- Use the ternary operator to test for empty strings or variables with no values assigned to them.
- Chain multiple ternary expressions together.
Sample code file: ternary.js
About the ternary ?:
operator
The ternary operator provides a concise alternative to writing multi-line if...else statements in JavaScript. The syntax is as follows:
condition ? ifTrue : ifFalse
So instead of writing:
const age = 21;
if (age >= 18) {
console.log("You may purchase beer.")
} else {
console.log("No beer for you.")
}
// Outputs: "You may purchase beer."
You could simply write:
const age = 21;
age >= 18 ? console.log("You may purchase beer.") : console.log("No beer for you.");
// Outputs: "You may purchase beer."
In this example:
- The variable being tested is age.
- The test condition is >= 18.
You could make this code easier to read by writing the two branches on separate lines:
const age = 21;
age >= 18
? console.log("You may purchase beer.")
: console.log("No beer for you.");
// Outputs: "You may purchase beer."
Or you could write everything on one line: the tested variable declaration, the condition, and the two branches:
const age = 21 >= 18 ? console.log("You may purchase beer.") : console.log("No beer for you.");
// Outputs: "You may purchase beer."
Most commonly, you will use the ternary operator to assign one of two possible values to a single variable depending on some condition.
Testing Booleans with the ternary operator
A typical use case for the ternary operator is to check a user's authentication status.
// Is user authenticated?
const isLoggedIn = true;
const greeting = isLoggedIn ? "Welcome back, User!" : "Please log in to continue.";
console.log(greeting);
// Outputs "Welcome back, User!"
A second typical usage is to check a toggle state.
// Is dark mode ON for this user?
const isDarkMode = true;
const toggleStatus = isDarkMode ? "Dark more is toggled ON." : "Dark more is toggled to OFF.";
console.log(toggleStatus); // "Dark more is toggled ON."
And is this case the ternary operator is used to provide a discounted price to members.
// Cheaper price for members
const isMember = true;
const price = isMember ? €9.99 : €12.99;
console.log(price);
// Outputs: €9.99
The test condition can include JavaScript's logical AND &&operator, which requires that both conditions must be true.
// Test multiple conditions with logical AND
const isUserLoggedIn = true;
const isAdmin = false;
const accessLevel = isUserLoggedIn && isAdmin ? "Admin" : "Regular User";
console.log("Access Level: " accessLevel);
// Outputs: "Access Level: Regular user"
Testing strings with the ternary operator
Here is the easiest-to-read version of testing a string variable with the ternary operator.
// Declaration of tested variable, test condition, and two branches on separate lines
const weather = "rainy";
weather === "sunny"
? console.log("Go out.")
: console.log("Stay home.");
// Outputs: "Stay home."
Below is a shorter version.
// Tested variable declared on separate line
const weather = "rainy";
weather === "sunny" ? console.log("Go out.") : console.log("Stay home.");
// Outputs: "Stay home."
And here is the most concise version.
// One line of code
const weather = "rainy" === "sunny" ? console.log("Go out.") : console.log("Stay home.");
// Outputs: "Stay home."
Test if a string is long or short based on a length condition.
// Is string short or long?
const str = "Hello";
const lengthDescription = (str.length > 5) ? "long" : "short";
console.log(lengthDescription); // Outputs: "short"
Check if a string contains a particular word:
// Does string contain 'fox'?
const sentence = "The quick brown fox jumps over the lazy dog.";
const containsFox = (sentence.includes("fox"))
? "contains 'fox'"
: "does not contain 'fox'";
console.log(containsFox); // Outputs: "contains 'fox'"
Check if a string starts with a certain letter or letters.
// Does product name start with 'TV_'?
const productName = "TV_Samsung_Model_X";
const category = (productName.startsWith("TV_")) ? "Television" : "Other";
console.log(category); // Outputs: "Television"
Testing numbers with the ternary operator
Which of two numbers is larger? The ternary operator can decide.
// Which of two numbers is larger?
const num1 = 10;
const num2 = 20;
const largerNumber = num1 > num2 ? num1 : num2;
console.log("The larger number is:" +largerNumber);
//Outputs: "The larger number is: 20"
Is a supplied number is odd or even? Again, the ternary operator can help.
// Is a number odd or even?
const number = 5;
const result = (number % 2 === 0) ? "even" : "odd";
console.log(result); // "odd"
Testing for ‘problem’ variables with the ternary operator
The ternary operator can help you find values that may generate errors in your code. Typically, these are empty strings or variables with no values assigned to them.
In each such case, you may want to assign some default value to the ‘problem’ variable.
Dealing with empty strings
Here is an example of assigning a default value to an empty string.
// Is string empty?
let userEmail = '';
let response = userEmail ? userEmail: "No email supplied."
console.log(response);
// Outputs: "No email supplied."
Dealing with variables that have no values assigned
In JavaScript the let keyword allows you to declare a variable without assigning a value to it. For example:
let userFirstName;
If a tested variable has no value assigned to it, the ternary expression evaluates to false:
// Is value assigned?
let isThereSoup;
let response = isThereSoup ? "Yes, we have soup": "No soup today."
console.log(response);
// Outputs: "No soup today."
Chaining and the ternary operator
In the example below a second ternary expression is chained to the false branch of the first ternary expression:
// Branching within the outer FALSE condition
const myNumber = 10;
let testNum = myNumber === 0 ? "You have nothing" : myNumber > 10 ? "You have a lot" : "You have a little";
console.log(testNum);
// Outputs: "You have a little"
To make this code easier to read, you could rewrite it over multiple lines as follows:
// Branching within the outer FALSE condition
const myNumber = 10;
let testNum = myNumber === 0
? "You have nothing"
: myNumber > 10
? "You have a lot"
: "You have a little"
console.log(testNum);
// Outputs: "You have a little"
And here is a second example of chaining ternary operators.
// Performing a double check
const firstCheck = false;
const secondCheck = false;
const grantAccess = firstCheck
? "Access denied"
: secondCheck
? "Access denied"
: "Access granted";
console.log(grantAccess);
// Outputs: "Access denied"