JavaScript is one of the most versatile programming languages, constantly evolving to simplify programming and enhance developer productivity. One of the latest additions to JavaScript is the question mark operator, denoted as ?
. Also known as the conditional operator, it provides a concise way to handle conditional statements in our code. Let’s look at how to write and use the question mark operator.
?
operatorThe ?
operator is a shorthand for an if-else
statement, making it a valuable tool for writing cleaner, shorter, and more readable code. It allows us to assign values or execute code based on a condition in a single line without writing separate if
and else
blocks.
This is how we use the ?
operator:
condition ? expressionIfTrue : expressionIfFalse
condition
: This is the expression that evaluates to either true or false.
expressionIfTrue
: This is the value or expression to be returned if the condition is true.
expressionIfFalse
: This is the value or expression to be returned if the condition is false.
Let's take a look at the rudimentary use of the question mark operator.
const age = 29;const isAdult = age > 18 ? 'Yes' : 'No'; // The operator checks if the age is greater than 18.console.log(`Is the person an adult? ${isAdult}`);
In this example, we determine whether a person is an adult based on their age using the ?
operator. If the age is greater than 18, isAdult
will be assigned the value Yes
; otherwise, it will be assigned No
.
The question mark operator can also be used inside a function call to make decisions based on the parameters passed in the function.
function greetUser(name, isFemale) {const gender = isFemale ? 'Ms.' : 'Mr.'; // The operator checks if gender is male or female.console.log(`Hello, ${gender} ${name}!`);}greetUser('Sam', true);greetUser('Mike', false);
In this example, we use the ?
operator to conditionally assign the appropriate title based on the isFemale
parameter in the greetUser
function. If isFemale
is true
, then the Ms.
title is assigned to gender
, otherwise the Mr.
title is assigned.
The question mark operator also gives us an additional benefit of handling default values, i.e, if the variable has not been assigned any value by the user, meaning that the value of the variable is null
, the operator can then assign a predefined default value to it.
function getUserRole(user) {const role = user.role ? user.role : 'Guest'; // The ? operator checks if role is assigned, if not it assigns Guest as default role.return `User role: ${role}`;}const userA = { name: 'Sam', role: 'Admin' };const userB = { name: 'David' };console.log(getUserRole(userA));console.log(getUserRole(userB));
In this example, we use the ?
operator to ensure that a default value is assigned to a property if the user does not provide it. It checks if a role is assigned to the user object. If no role is assigned, it provides the default value Guest
.
We also have the ability to chain multiple conditions together (just like we can in if
statements), using the &&
or ||
operators.
const cGPA = 3.2;const finalSem = true;const canGraduate = cGPA >= 2.0 && finalSem ? 'Allowed' : 'Not allowed';console.log(`Can the student graduate? ${canGraduate}`);
This example demonstrates how we can chain multiple conditions together using the &&
operator. Here, we are checking whether a student is allowed to graduate or not by checking the values of cGPA
and finalSem
. If their cGPA
is greater than 2.0
, and their finalSem
status is true
, only then they will be allowed to graduate.
We can also chain multiple if
conditions (equivalent to else-if
statements) using the question mark operator.
const isFresh = false;const isSoph = true;const isJun = false;const yearLevel = isFresh ? 'Freshmen': isSoph ? 'Sophomore': isJun ? 'Junior': 'Senior';console.log(`The student is a ${yearLevel}`);
In this example, we check the three conditions isFresh
, isSoph
, and isJun
. Depending on which condition is true, a value is assigned to yearLevel
.
The JavaScript ?
operator simplifies our code by condensing conditional statements into concise, one-liners. By using it wisely, we can enhance the readability and maintainability of our JavaScript code. Whether we are working with variables, function calls, or default values, the ?
operator can be a powerful addition to our JavaScript toolkit, helping us write more efficient and elegant code.
Free Resources