How to Use the Ternary Operator in JavaScript – Explained with Examples
Tired of bulky if-else statements? JavaScript's ternary operator offers a powerful solution. This handy tool lets you condense complex conditional logic into a single line, making your code cleaner, more elegant, and efficient.
In this article, we'll take a deep dive into the ternary operator, understanding its syntax and showcasing real-world examples to help you understand how it works to harness its full potential.
Here is What We'll Cover:
What is a ternary operator, how to use the ternary operator.
- How to Refactor if-else Statements to Ternary operator
How to Chain Ternary Operators
- Best Practices when using the Ternary Operator
A ternary operator is a conditional operator in JavaScript that evaluates a conditional expression and returns either a truthy or falsy value.
To understand how this works, let's take a closer look at its syntax below:
From the syntax above, the condionalExpression is the expression that serves as the evaluation point, determining either a truthy or falsy value.
Following the ? (question mark), the value provided is returned in case the expression evaluates to truthy, whereas the value following the : (colon) is returned if the expression results in a falsy outcome.
The truthyValue and falsyValue can be anything in JavaScript. It can encompass various entities such as functions, values stored in variables, objects, numbers, strings, and more. The ternary operator grants you the flexibility to return any desired value, offering versatility in your code.
Now that we've examined the syntax and its functionality, let's explore how to use the ternary operator to deepen our understanding.
Consider this scenario: we're building a gaming platform that only allows users that are aged 18 and above. We'll design a function to check a user's age. If they're under 18, they'll be denied access; otherwise, they'll gain entry to the platform.
From the code snippet above, we created a function, canAccessPlatform , which evaluates whether a user, represented by their age parameter, meets the requirement to access the platform.
It utilizes a ternary operator to determine if the age is 18 or older, assigning true to shouldAccess if the condition is met, and false otherwise. Finally, it returns the value of shouldAccess , indicating whether the user can access the platform or not.
If the age is 18 or older, the expression becomes true, so the operator returns true after the ? . Otherwise, it returns false. This result is saved in a variable and then returned from the function.
While this basic use case simplifies code and improves readability by replacing unnecessary if-else blocks, it's important to use it sparingly to avoid cluttering and complicating your code. Later, we'll discuss best practices for using the ternary operator.
Here's another example illustrating the use of the ternary operator. We'll create a function to determine whether a number is even or odd. Check out the code snippet below:
From the code snippet above:
- We define a function checkEvenOrOdd that takes a number parameter.
- Inside the function, we use the ternary operator to check if the number is even or odd.
- If the number modulo 2 equals 0 (meaning it's divisible by 2 with no remainder), then the condition evaluates to true, and the string "even" is assigned to the result variable.
- If the condition evaluates to false (meaning the number is odd), the string "odd" is assigned to result .
- Finally, the function returns the value of result , which indicates whether the number is even or odd.
This code shows how the ternary operator quickly checks if a number is even or odd, making the code easier to read and understand.
How to Refactor if-else Statements to Ternary Operator
An advantage of the ternary operator is avoiding unnecessary if-else blocks, which can complicate code readability and maintenance. In this section, we'll refactor some if-else statements into ternary operations, providing a clearer understanding of how to use ternary operators effectively.
Let's start with our first example:
This function, decideActivity , takes a weather parameter and determines the appropriate activity based on the weather condition.
If the weather is "sunny", it suggests to "go out". Otherwise, it advises to "stay in". When we call the function with different weather conditions like "raining" or "snowing", it outputs the corresponding activity recommendation using console.log() .
For instance, calling decideActivity("raining") will output "stay in". Similarly, decideActivity("snowing") also outputs "stay in". When decideActivity("sunny") is called, it outputs "go out". This straightforward function helps decide on activities based on the weather condition provided.
Now, we can refactor these blocks of code to make them look simpler and neater. Let's see how to do that below:
From the code sample above, this function, decideActivity , uses the ternary operator to quickly determine the activity based on the weather condition. It checks if the weather is "sunny" and assigns "go out" if true, otherwise "stay in".
We've simplified the if-else statements into a one-liner ternary operator. This makes our code cleaner, clearer, and easier to read.
Let take a look at another example:
Let's explain what the code above is doing:
- Function Definition : We begin by defining a function named checkNumber that takes a single parameter called number .
- Variable Declaration : Inside the function, we declare a variable named result without assigning any value to it yet. This variable will store the result of our check.
- Conditional Statement (if-else) : We have a conditional statement that checks whether the number parameter is greater than 0.
- If the condition is true (meaning the number is positive), we assign the string "positive" to the result variable.
- If the condition is false (meaning the number is not positive, (meaning it is either negative or zero), we assign the string "non-positive" to the result variable.
- Return Statement : Finally, we return the value stored in the result variable.
- Function Calls :We then call the checkNumber function twice with different arguments: 5 and -2.
When we call checkNumber(5) , the function returns "positive", which is then logged to the console.
Similarly, when we call checkNumber(-2) , the function returns "non-positive", which is again logged to the console.
This function efficiently determines whether a number is positive or non-positive and provides the appropriate result based on the condition.
Let's simplify and improve the code by rewriting it using a ternary operator.
Great job! By refactoring the function and utilizing the ternary operator for conditional evaluation, we've achieved cleaner, more concise, and readable code.
This code, using the ternary operator, feels more concise and elegant. It efficiently determines if a number is positive or non-positive, making the code cleaner and easier to understand. When we call checkNumber(5) , it returns "positive", while checkNumber(-2) returns "non-positive". Overall, the ternary operator enhances the code's readability.
When dealing with conditional checks, sometimes a single condition isn't enough. In such cases, we use 'else-if' statements alongside 'if/else' to incorporate multiple conditions.
Let's take a look at the syntax:
This can be translated into an if/else chain:
Let's explore an example below:
This code above defines a function called checkNumber that takes a number parameter and determines its status (positive, zero, or negative). It utilizes an if-else block with one else-if statement to evaluate the number's value. If the number is greater than 0, it's considered positive and if it's equal to 0, it's zero. Otherwise, it's negative. The function returns the result.
Let's refactor this code using a ternary operator to achieve the same functionality.
That's it! We've refactored the function, and upon closer examination, we can observe that the operators are chained together. Now, let's explore how the chained ternary operator works in the checkNumber function.
In the first ternary operator:
- The first part number > 0 checks if the number is greater than 0.
- If it's true, the expression returns "Positive".
In the second ternary operator (chained):
- If the first condition is false (meaning the number is not greater than 0), it moves to the next part of the expression: number === 0 .
- This part checks if the number is equal to 0.
- If it's true, the expression returns "Zero".
And the default value:
- If neither of the above conditions is true (meaning the number is not greater than 0 and not equal to 0), it defaults to the last part of the expression: "Negative" .
- This part acts as the default value if none of the preceding conditions are met.
In summary, the chained ternary operator evaluates multiple conditions in a single line of code. It checks each condition sequentially, and the first condition that evaluates to true determines the result of the entire expression. This allows for concise and efficient conditional logic.
Let's examine another example of a chained ternary operator.
In the given code sample, the ternary operators are chained together to provide different drink suggestions based on the age provided. Each conditional expression in the chain evaluates a specific age range.
If the first condition is true (truthy), it returns 'Enjoy a cocktail'. If false (falsy), it moves to the next conditional expression, and so on. This chaining process continues until a condition evaluates to true. If none of the conditions in the chain are true, the last value is returned as a fallback, similar to the 'else' block in an if/else statement.
The concept of 'chaining' ternary operators involves linking conditional expressions based on the value of the previous expression. This can be compared to the else if structure in an if/else statement, providing a concise way to handle multiple conditions in JavaScript.
Best Practices when Using the Ternary Operator
Using the ternary operator efficiently can significantly enhance code readability and conciseness. In this section, we'll explore key best practices for utilizing the ternary operator effectively.
- Keep it simple and readable : Write concise expressions that are easy to understand at a glance. Avoid nesting too many ternary operators or writing overly complex conditions.
- Use for simple assignments: Ternary operators are ideal for simple assignments where there are only two possible outcomes based on a condition. For more complex scenarios, consider using if/else statements.
- Know when to use it : Use the ternary operator when you need to perform a simple conditional check and assign a value based on the result. It's particularly useful for assigning default values or determining the value of a variable based on a condition.
- Test thoroughly : Test your code thoroughly to ensure that the ternary operator behaves as expected under different conditions. Check for edge cases and validate the correctness of the assigned values.
- Avoid nested ternaries: While chaining ternaries is possible, excessive nesting can lead to code that is difficult to read. Prefer clarity and consider using if/else for complex conditions.
- Keep ternaries short: Aim to keep ternary expressions short and concise. Long ternaries can be difficult to read and understand, leading to code maintenance challenges.
These best practices outline guidelines for effectively utilizing the ternary operator. While they are not strict rules, they offer valuable insights to enhance the clarity and readability of your code.
As we conclude this article, you've gained a comprehensive understanding of the ternary operator—its application in daily coding tasks, converting if/else statements, chaining operators, and best practices. I'm confident that you've acquired valuable insights that will enhance your coding practices using the ternary operator.
Thank you for reading, and see you next time!
Contact information
Would you like to get in touch with me? Don't hesitate to reach out through any of the following channels:
- Twitter / X: @developeraspire
- Email: [email protected]
A Frontend & Mobile Engineer with over 4 years of experience in the industry, I am passionate about creating engaging, user-friendly, and high-performing websites, mobile and web applications.
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- Remember language
- Português (do Brasil)
Expressions and operators
This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.
At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that purely evaluate .
The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to 7 .
The expression 3 + 4 is an example of the second type. This expression uses the + operator to add 3 and 4 together and produces a value, 7 . However, if it's not eventually part of a bigger construct (for example, a variable declaration like const z = 3 + 4 ), its result will be immediately discarded — this is usually a programmer mistake because the evaluation doesn't produce any effects.
As the examples above also illustrate, all complex expressions are joined by operators , such as = and + . In this section, we will introduce the following operators:
Assignment operators
Comparison operators, arithmetic operators, bitwise operators, logical operators, bigint operators, string operators, conditional (ternary) operator, comma operator, unary operators, relational operators.
These operators join operands either formed by higher-precedence operators or one of the basic expressions . A complete and detailed list of operators and expressions is also available in the reference .
The precedence of operators determines the order they are applied when evaluating an expression. For example:
Despite * and + coming in different orders, both expressions would result in 7 because * has precedence over + , so the * -joined expression will always be evaluated first. You can override operator precedence by using parentheses (which creates a grouped expression — the basic expression). To see a complete table of operator precedence as well as various caveats, see the Operator Precedence Reference page.
JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:
For example, 3 + 4 or x * y . This form is called an infix binary operator, because the operator is placed between two operands. All binary operators in JavaScript are infix.
A unary operator requires a single operand, either before or after the operator:
For example, x++ or ++x . The operator operand form is called a prefix unary operator, and the operand operator form is called a postfix unary operator. ++ and -- are the only postfix operators in JavaScript — all other operators, like ! , typeof , etc. are prefix.
An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .
There are also compound assignment operators that are shorthand for the operations listed in the following table:
Assigning to properties
If an expression evaluates to an object , then the left-hand side of an assignment expression may make assignments to properties of that expression. For example:
For more information about objects, read Working with Objects .
If an expression does not evaluate to an object, then assignments to properties of that expression do not assign:
In strict mode , the code above throws, because one cannot assign properties to primitives.
It is an error to assign values to unmodifiable properties or to properties of an expression without properties ( null or undefined ).
Destructuring
For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
Without destructuring, it takes multiple statements to extract values from arrays and objects:
With destructuring, you can extract multiple values into distinct variables using a single statement:
Evaluation and nesting
In general, assignments are used within a variable declaration (i.e., with const , let , or var ) or as standalone statements.
However, like other expressions, assignment expressions like x = f() evaluate into a result value. Although this result value is usually not used, it can then be used by another expression.
Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, some JavaScript style guides discourage chaining or nesting assignments . Nevertheless, assignment chaining and nesting may occur sometimes, so it is important to be able to understand how they work.
By chaining or nesting an assignment expression, its result can itself be assigned to another variable. It can be logged, it can be put inside an array literal or function call, and so on.
The evaluation result matches the expression to the right of the = sign in the "Meaning" column of the table above. That means that x = f() evaluates into whatever f() 's result is, x += f() evaluates into the resulting sum x + f() , x **= f() evaluates into the resulting power x ** f() , and so on.
In the case of logical assignments, x &&= f() , x ||= f() , and x ??= f() , the return value is that of the logical operation without the assignment, so x && f() , x || f() , and x ?? f() , respectively.
When chaining these expressions without parentheses or other grouping operators like array literals, the assignment expressions are grouped right to left (they are right-associative ), but they are evaluated left to right .
Note that, for all assignment operators other than = itself, the resulting values are always based on the operands' values before the operation.
For example, assume that the following functions f and g and the variables x and y have been declared:
Consider these three examples:
Evaluation example 1
y = x = f() is equivalent to y = (x = f()) , because the assignment operator = is right-associative . However, it evaluates from left to right:
- The y on this assignment's left-hand side evaluates into a reference to the variable named y .
- The x on this assignment's left-hand side evaluates into a reference to the variable named x .
- The function call f() prints "F!" to the console and then evaluates to the number 2 .
- That 2 result from f() is assigned to x .
- The assignment expression x = f() has now finished evaluating; its result is the new value of x , which is 2 .
- That 2 result in turn is also assigned to y .
- The assignment expression y = x = f() has now finished evaluating; its result is the new value of y – which happens to be 2 . x and y are assigned to 2 , and the console has printed "F!".
Evaluation example 2
y = [ f(), x = g() ] also evaluates from left to right:
- The y on this assignment's left-hand evaluates into a reference to the variable named y .
- The function call g() prints "G!" to the console and then evaluates to the number 3 .
- That 3 result from g() is assigned to x .
- The assignment expression x = g() has now finished evaluating; its result is the new value of x , which is 3 . That 3 result becomes the next element in the inner array literal (after the 2 from the f() ).
- The inner array literal [ f(), x = g() ] has now finished evaluating; its result is an array with two values: [ 2, 3 ] .
- That [ 2, 3 ] array is now assigned to y .
- The assignment expression y = [ f(), x = g() ] has now finished evaluating; its result is the new value of y – which happens to be [ 2, 3 ] . x is now assigned to 3 , y is now assigned to [ 2, 3 ] , and the console has printed "F!" then "G!".
Evaluation example 3
x[f()] = g() also evaluates from left to right. (This example assumes that x is already assigned to some object. For more information about objects, read Working with Objects .)
- The x in this property access evaluates into a reference to the variable named x .
- Then the function call f() prints "F!" to the console and then evaluates to the number 2 .
- The x[f()] property access on this assignment has now finished evaluating; its result is a variable property reference: x[2] .
- Then the function call g() prints "G!" to the console and then evaluates to the number 3 .
- That 3 is now assigned to x[2] . (This step will succeed only if x is assigned to an object .)
- The assignment expression x[f()] = g() has now finished evaluating; its result is the new value of x[2] – which happens to be 3 . x[2] is now assigned to 3 , and the console has printed "F!" then "G!".
Avoid assignment chains
Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, chaining assignments in the same statement is discouraged .
In particular, putting a variable chain in a const , let , or var statement often does not work. Only the outermost/leftmost variable would get declared; other variables within the assignment chain are not declared by the const / let / var statement. For example:
This statement seemingly declares the variables x , y , and z . However, it only actually declares the variable z . y and x are either invalid references to nonexistent variables (in strict mode ) or, worse, would implicitly create global variables for x and y in sloppy mode .
A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:
Note: => is not a comparison operator but rather is the notation for Arrow functions .
An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:
In addition to the standard arithmetic operations ( + , - , * , / ), JavaScript provides the arithmetic operators listed in the following table:
A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
The following table summarizes JavaScript's bitwise operators.
Bitwise logical operators
Conceptually, the bitwise logical operators work as follows:
The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:
Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
The operator is applied to each pair of bits, and the result is constructed bitwise.
For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:
Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation). ~x evaluates to the same value that -x - 1 evaluates to.
Bitwise shift operators
The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.
Shift operators convert their operands to thirty-two-bit integers and return a result of either type Number or BigInt : specifically, if the type of the left operand is BigInt , they return BigInt ; otherwise, they return Number .
The shift operators are listed in the following table.
Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && , || , and ?? operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. As such, they are more adequately called "value selection operators". The logical operators are described in the following table.
Examples of expressions that can be converted to false are those that evaluate to null , 0 , 0n , NaN , the empty string ( "" ), or undefined .
The following code shows examples of the && (logical AND) operator.
The following code shows examples of the || (logical OR) operator.
The following code shows examples of the ?? (nullish coalescing) operator.
Note how ?? works like || , but it only returns the second expression when the first one is " nullish ", i.e. null or undefined . ?? is a better alternative than || for setting defaults for values that might be null or undefined , in particular when values like '' or 0 are valid values and the default should not apply.
The following code shows examples of the ! (logical NOT) operator.
Short-circuit evaluation
As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:
- falsy && anything is short-circuit evaluated to the falsy value.
- truthy || anything is short-circuit evaluated to the truthy value.
- nonNullish ?? anything is short-circuit evaluated to the non-nullish value.
The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.
Most operators that can be used between numbers can be used between BigInt values as well.
One exception is unsigned right shift ( >>> ) , which is not defined for BigInt values. This is because a BigInt does not have a fixed width, so technically it does not have a "highest bit".
BigInts and numbers are not mutually replaceable — you cannot mix them in calculations.
This is because BigInt is neither a subset nor a superset of numbers. BigInts have higher precision than numbers when representing large integers, but cannot represent decimals, so implicit conversion on either side might lose precision. Use explicit conversion to signal whether you wish the operation to be a number operation or a BigInt one.
You can compare BigInts with numbers.
In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
For example,
The shorthand assignment operator += can also be used to concatenate strings.
The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:
If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.
This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .
The comma operator ( , ) evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop. It is regarded bad style to use it elsewhere, when it is not necessary. Often two separate statements can and should be used instead.
For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:
A unary operation is an operation with only one operand.
The delete operator deletes an object's property. The syntax is:
where object is the name of an object, property is an existing property, and propertyKey is a string or symbol referring to an existing property.
If the delete operator succeeds, it removes the property from the object. Trying to access it afterwards will yield undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.
Deleting array elements
Since arrays are just objects, it's technically possible to delete elements from them. This is, however, regarded as a bad practice — try to avoid it. When you delete an array property, the array length is not affected and other elements are not re-indexed. To achieve that behavior, it is much better to just overwrite the element with the value undefined . To actually manipulate the array, use the various array methods such as splice .
The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.
Suppose you define the following variables:
The typeof operator returns the following results for these variables:
For the keywords true and null , the typeof operator returns the following results:
For a number or string, the typeof operator returns the following results:
For property values, the typeof operator returns the type of value the property contains:
For methods and functions, the typeof operator returns results as follows:
For predefined objects, the typeof operator returns results as follows:
The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them to avoid precedence issues.
A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.
The in operator returns true if the specified property is in the specified object. The syntax is:
where propNameOrNumber is a string, numeric, or symbol expression representing a property name or array index, and objectName is the name of an object.
The following examples show some uses of the in operator.
The instanceof operator returns true if the specified object is of the specified object type. The syntax is:
where object is the object to test against objectType , and objectType is a constructor representing a type, such as Date or Array .
Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.
For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.
Basic expressions
All operators eventually operate on one or more basic expressions. These basic expressions include identifiers and literals , but there are a few other kinds as well. They are briefly introduced below, and their semantics are described in detail in their respective reference sections.
Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:
Suppose a function called validate validates an object's value property, given the object and the high and low values:
You could call validate in each form element's onChange event handler, using this to pass it to the form element, as in the following example:
Grouping operator
The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.
Property accessor
The property accessor syntax gets property values on objects, using either dot notation or bracket notation.
The working with objects guide goes into more details about object properties.
Optional chaining
The optional chaining syntax ( ?. ) performs the chained operation on an object if it is defined and non- null , and otherwise short-circuits the operation and returns undefined . This allows you to operate on a value that may be null or undefined without causing a TypeError .
You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:
The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.
Quick Tip: How to Use the Ternary Operator in JavaScript
Share this article
Key Takeaways
Using the ternary operator for value assignment, using the ternary operator for executing expressions, using the ternary operator for null checks, nested conditions, codepen example, faqs on how to use the ternary operator in javascript.
In this tutorial, we’ll explore the syntax of the ternary operator in JavaScript and some of its common uses.
The ternary operator (also known as the conditional operator ) can be used to perform inline condition checking instead of using if...else statements. It makes the code shorter and more readable. It can be used to assign a value to a variable based on a condition, or execute an expression based on a condition.
- The ternary operator in JavaScript allows for inline condition checking, making code shorter and more readable. It accepts three operands: a condition to test, and two expressions separated by a colon. The first expression is executed if the condition is true, and the second if the condition is false.
- The ternary operator can be used for value assignment, executing expressions based on a condition, and checking if a variable is null or undefined. It can also handle multiple conditions, similar to if…else if…else statements, by nesting or chaining conditions within the operator’s expressions.
- While the ternary operator can increase code readability by replacing lengthy if…else statements, overuse of nested ternary operators can make code harder to read. It’s also important to note that the ternary operator requires both a true and a false branch.
The ternary operator accepts three operands; it’s the only operator in JavaScript to do that. You supply a condition to test, followed by a questions mark, followed by two expressions separated by a colon. If the condition is considered to be true ( truthy ), the first expression is executed; if it’s considered to be false, the final expression is executed.
It’s used in the following format:
Here, condition is the condition to test. If its value is considered to be true , expr1 is executed. Otherwise, if its value is considered to be false , expr2 is executed.
expr1 and expr2 are any kind of expression. They can be variables, function calls, or even other conditions.
For example:
One of the most common use cases of ternary operators is to decide which value to assign to a variable. Often, a variable’s value might depend on the value of another variable or condition.
Although this can be done using the if...else statement, it can make the code longer and less readable. For example:
In this code example, you first define the variable message . Then, you use the if...else statement to determine the value of the variable.
This can be simply done in one line using the ternary operator:
Ternary operators can be used to execute any kind of expression.
For example, if you want to decide which function to run based on the value of a variable, you can do it like this using the if...else statement:
This can be done in one line using the ternary operator:
If feedback has the value yes , then the sayThankYou function will be called and executed. Otherwise, the saySorry function will be called and executed.
In many cases, you might be handling variables that may or may not have a defined value — for example, when retrieving results from user input, or when retrieving data from a server.
Using the ternary operator, you can check that a variable is not null or undefined just by passing the variable name in the position of the condition operand.
This is especially useful when the variable is an object . If you try to access a property on an object that’s actually null or undefined , an error will occur. Checking that the object is actually set first can help you avoid errors.
In the first part of this code block, book is an object with two properties — name and author . When the ternary operator is used on book , it checks that it’s not null or undefined . If it’s not — meaning it has a value — the name property is accessed and logged into the console. Otherwise, if it’s null, No book is logged into the console instead.
Since book is not null , the name of the book is logged in the console. However, in the second part, when the same condition is applied, the condition in the ternary operator will fail, since book is null . So, “No book” will be logged in the console.
Although ternary operators are used inline, multiple conditions can be used as part of a ternary operator’s expressions. You can nest or chain more than one condition to perform condition checks similar to if...else if...else statements.
For example, a variable’s value may depend on more than one condition. It can be implemented using if...else if...else :
In this code block, you test multiple conditions on the score variable to determine the letter grading of the variable.
These same conditions can be performed using ternary operators as follows:
The first condition is evaluated, which is score < 50 . If it’s true , then the value of grade is F . If it’s false , then the second expression is evaluated which is score < 70 .
This keeps going until either all conditions are false , which means the grade’s value will be A , or until one of the conditions is evaluated to be true and its truthy value is assigned to grade .
In this live example, you can test how the ternary operator works with more multiple conditions.
If you enter a value less than 100, the message “Too Low” will be shown. If you enter a value greater than 100, the message “Too High” will be shown. If you enter 100, the message “Perfect” will be shown.
See the Pen Ternary Operator in JS by SitePoint ( @SitePoint ) on CodePen .
As explained in the examples in this tutorial, the ternary operator in JavaScript has many use cases. In many situations, the ternary operator can increase the readability of our code by replacing lengthy if...else statements.
Related reading:
- 25+ JavaScript Shorthand Coding Techniques
- Quick Tip: How to Use the Spread Operator in JavaScript
- Back to Basics: JavaScript Object Syntax
- JavaScript: Novice to Ninja
What is the Syntax of the Ternary Operator in JavaScript?
The ternary operator in JavaScript is a shorthand way of writing an if-else statement. It is called the ternary operator because it takes three operands: a condition, a result for true, and a result for false. The syntax is as follows: condition ? value_if_true : value_if_false In this syntax, the condition is an expression that evaluates to either true or false. If the condition is true, the operator returns the value_if_true . If the condition is false, it returns the value_if_false .
Can I Use Multiple Ternary Operators in a Single Statement?
Yes, you can use multiple ternary operators in a single statement. This is known as “nesting”. However, it’s important to note that using too many nested ternary operators can make your code harder to read and understand. Here’s an example of how you can nest ternary operators: let age = 15; let beverage = (age >= 21) ? "Beer" : (age < 18) ? "Juice" : "Cola"; console.log(beverage); // Output: "Juice"
Can Ternary Operators Return Functions in JavaScript?
Yes, the ternary operator can return functions in JavaScript. This can be useful when you want to execute different functions based on a condition. Here’s an example: let greeting = (time < 10) ? function() { alert("Good morning"); } : function() { alert("Good day"); }; greeting();
How Does the Ternary Operator Compare to If-Else Statements in Terms of Performance?
In terms of performance, the difference between the ternary operator and if-else statements is negligible in most cases. Both are used for conditional rendering, but the ternary operator can make your code more concise.
Can Ternary Operators be Used Without Else in JavaScript?
No, the ternary operator in JavaScript requires both a true and a false branch. If you don’t need to specify an action for the false condition, consider using an if statement instead.
How Can I Use the Ternary Operator with Arrays in JavaScript?
You can use the ternary operator with arrays in JavaScript to perform different actions based on the condition. Here’s an example: let arr = [1, 2, 3, 4, 5]; let result = arr.length > 0 ? arr[0] : 'Array is empty'; console.log(result); // Output: 1
Can Ternary Operators be Used for Multiple Conditions?
Yes, you can use ternary operators for multiple conditions. However, it can make your code harder to read if overused. Here’s an example: let age = 20; let type = (age < 13) ? "child" : (age < 20) ? "teenager" : "adult"; console.log(type); // Output: "teenager"
Can Ternary Operators be Used in Return Statements?
Yes, you can use ternary operators in return statements. This can make your code more concise. Here’s an example: function isAdult(age) { return (age >= 18) ? true : false; } console.log(isAdult(20)); // Output: true
Can Ternary Operators be Used with Strings in JavaScript?
Yes, you can use ternary operators with strings in JavaScript. Here’s an example: let name = "John"; let greeting = (name == "John") ? "Hello, John!" : "Hello, Stranger!"; console.log(greeting); // Output: "Hello, John!"
Can Ternary Operators be Used with Objects in JavaScript?
Yes, you can use ternary operators with objects in JavaScript. Here’s an example: let user = { name: "John", age: 20 }; let greeting = (user.age >= 18) ? "Hello, Adult!" : "Hello, Kid!"; console.log(greeting); // Output: "Hello, Adult!"
Dianne is SitePoint's newsletter editor. She especiallly loves learning about JavaScript, CSS and frontend technologies.
IMAGES
VIDEO