• Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Conditional (ternary) operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy . This operator is frequently used as an alternative to an if...else statement.

An expression whose value is used as a condition.

An expression which is executed if the condition evaluates to a truthy value (one which equals or can be converted to true ).

An expression which is executed if the condition is falsy (that is, has a value which can be converted to false ).

Description

Besides false , possible falsy expressions are: null , NaN , 0 , the empty string ( "" ), and undefined . If condition is any of these, the result of the conditional expression will be the result of executing the expression exprIfFalse .

A simple example

Handling null values.

One common usage is to handle a value that may be null :

Conditional chains

The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain:

This is equivalent to the following if...else chain.

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Nullish coalescing operator ( ?? )
  • Optional chaining ( ?. )
  • Making decisions in your code — conditionals
  • Expressions and operators guide

Dianne Pena

Quick Tip: How to Use the Ternary Operator in JavaScript

Share this article

Quick Tip: How to Use the Ternary Operator in JavaScript

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 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.

SitePoint Premium

MarketSplash

Unraveling The JavaScript Ternary Operator: An In-Depth Guide For Efficient Coding

From web development to data processing, JavaScript's ternary operator offers a concise way to handle conditional logic. Discover its intricate details, real-world applications, and the art of using it efficiently.

💡 KEY INSIGHTS

  • The ternary operator in JavaScript provides a concise way to execute code based on a boolean condition, replacing traditional if-else statements.
  • It consists of three parts: a condition , a result upon true (then), and a result upon false (else), making code more readable for simple conditions.
  • While useful for simple, inline conditional logic, ternary operators can reduce readability when nested or used for complex conditions.
  • Ternary operators are often used for assignment and decision-making in a single line, enhancing the succinctness of the code.

assignment with ternary operator

Basics Of Javascript Ternary

Syntax and structure, common use cases, comparison with if-else statements, best practices and pitfalls, advanced ternary techniques, real-world examples, frequently asked questions, basic syntax, ternary vs. if-else, optimal scenarios for ternary, avoiding overuse.

The ternary operator in JavaScript acts as a shorthand for conditional statements. It's concise and simplifies decision-making in code, especially when we want to assign a value based on a condition.

Syntax Spotlight

The structure of the ternary operator is straightforward:

condition ? valueIfTrue : valueIfFalse;

Here's an example to determine the type of a number:

While both can be used for conditional checks, the ternary operator shines when you need quick assignments based on conditions. It makes your code cleaner and easier to read for these specific cases. However, for more complex decision trees, traditional if-else structures might be more suitable.

  • Quick evaluations and assignments.
  • Replacing single-level if-else checks.
  • Short inline conditions in functions.

Though the ternary operator is a valuable tool, it's essential to avoid overusing it. It's not ideal for:

  • Multi-layered conditional checks.
  • Situations where the outcome isn't about assignment or return.
  • Any case where its use might reduce code clarity.

Balancing brevity with clarity is crucial. The ternary operator is a testament to this principle in JavaScript, enabling us to write clean and efficient code when used thoughtfully.

Conditional Rendering in Frameworks

Handling default values, enhancing readability.

The ternary operator in JavaScript provides a quick and concise way to perform conditional checks. The simplicity of its structure is what lends it the name "ternary", meaning composed of three parts.

At its core, the ternary operator is represented as:

For clarity, consider a scenario where we want to determine the maximum of two numbers:

Nested Ternary

You can also nest ternary operators, but caution is advised to maintain readability. Nesting involves placing one ternary expression within another:

Breaking Down Components

  • Condition : This is the decision-making part. It evaluates to either true or false.
  • ValueIfTrue : If the condition is true, this expression or value gets executed or assigned.
  • ValueIfFalse : Conversely, if the condition is false, this is the part that gets executed or assigned.

To ensure that your code remains clear:

  • Limit the nesting of ternary operators.
  • Use parentheses for clarity when mixing with other operators.
  • Avoid using ternary for very complex conditions; instead, opt for traditional conditional statements.

Remember, while the ternary operator offers brevity, it shouldn't come at the cost of clarity. Proper usage can lead to more understandable and maintainable code.

Assigning Values Based on Conditions

Inline function returns, limitations and considerations.

The ternary operator offers developers a concise way to execute conditional tasks. Here, we'll look at several scenarios where its application can streamline your code and make it more readable.

A frequent usage of the ternary operator is to assign a value to a variable based on some condition:

Frameworks like React utilize the ternary operator for conditional rendering:

Another practical use case is to set default values, especially when dealing with potential undefined or null values:

Or using the newer nullish coalescing:

In functions that require a quick conditional return value, the ternary operator can be very effective:

While the ternary operator shines in these scenarios, it's crucial to recognize its boundaries:

  • It's ideal for situations with clear binary outcomes.
  • For conditions with more than two outcomes, chaining multiple ternaries can compromise readability.
  • It's not suited for executing multiple statements based on a condition; traditional conditional statements are better in such cases.

The ternary operator, when employed correctly, can significantly reduce verbosity and improve clarity. But as with all tools, judicious use is essential.

The Ternary Operator

If-else statements, making the right choice.

Both the ternary operator and if-else statements serve the purpose of conditional execution in JavaScript. However, they have distinct characteristics that make them suitable for different scenarios.

The ternary operator is concise and specifically designed for situations where you need to make a decision between two outcomes, primarily for assignments:

  • Brevity in assignments based on conditions.
  • Excellent for inline conditions and rendering.
  • Simplifies setting default values.

Weaknesses:

  • Not suited for multi-level conditions.
  • Can compromise readability when overused or nested excessively.

The if-else statement provides a more detailed structure and can handle multiple conditions and outcomes:

  • Versatility in handling multiple conditions and outcomes.
  • Clear and detailed structure, especially for multi-statement outcomes.
  • Ideal for executing more complex logic based on conditions.
  • More verbose compared to the ternary operator for simple conditions.

When deciding between the two:

  • Opt for the ternary operator for straightforward, binary decisions, especially for assignments.
  • Choose if-else for more intricate scenarios with multiple potential outcomes or when more than two simple actions need to be taken.

In programming, selecting the right tool for the task at hand is essential. Recognizing when to employ the ternary operator and when to utilize if-else ensures your code remains efficient and readable.

assignment with ternary operator

Maintain Readability

Limit nesting, use parentheses for clarity, avoid side effects, pitfalls to watch out for, clarity above all.

Navigating the ternary operator is relatively straightforward. However, understanding its potential pitfalls and adhering to best practices ensures you get the most out of it without compromising code clarity.

While the ternary operator is a tool of brevity, it shouldn't sacrifice readability:

Nesting ternaries can quickly lead to confusion. If you find yourself considering nested ternaries, it might be time to rethink:

When combining the ternary operator with other operators, use parentheses to denote priority:

The ternary operator should ideally be used for expressions, not statements. Avoid triggering side effects:

  • Overuse : The ternary operator is powerful, but that doesn’t mean it should replace every if-else scenario.
  • Misunderstanding Precedence : Without proper parentheses, you might encounter unexpected results due to operator precedence.
  • Overlooking Type Coercion : JavaScript has dynamic typing, and sometimes the ternary operator can yield unexpected results if not cautious.

While the ternary operator offers a more concise way to write conditional statements, always prioritize clarity. Ensure anyone reading your code, including your future self, can quickly grasp its logic. This balance between brevity and understanding is where the real power of the ternary operator lies.

Multiple Operations within a Ternary

Combining with logical operators, short-circuit evaluation, chained ternary, ternaries and arrow functions, consider performance, always aim for balance.

For those already comfortable with the basic use of the ternary operator , there are advanced techniques that can further enhance its utility in your codebase.

It's possible to execute more than one operation within each part of a ternary by using the comma operator:

Logical operators, such as && and || , can be combined with ternaries for more intricate conditional outcomes:

Benefit from the properties of logical operators to create short-circuit evaluations:

While this isn’t always recommended due to potential readability concerns, chaining is possible:

When used within arrow functions, ternaries can provide a quick return based on conditions:

While the ternary operator is highly efficient, excessive chaining or complex nesting can have performance implications, especially in tight loops or performance-critical applications.

Advanced techniques are tools to make your code more efficient, but they should never compromise clarity. It's always essential to strike a balance between leveraging advanced techniques and ensuring your code remains readable and maintainable. Advanced ternary techniques can be powerful, but they're most effective when applied judiciously.

Dynamic Styling in Web Development

User feedback in forms, configuring display settings, routing in web applications, setting default values, a tool for everyday coding.

The ternary operator isn't just a neat trick in textbooks; it’s regularly employed in real-world projects for its concise syntax and straightforward logic. Here are some pragmatic scenarios where the ternary shines.

When developing websites, dynamic styling based on certain conditions is common. Consider a button that changes color based on a user's actions:

This method quickly assigns a color to the button based on the isClicked status.

Handling user feedback is crucial in form validations. Using ternaries, you can provide instant responses:

In applications with customizable display settings, ternaries can help set display modes:

Direct users based on their authentication status or roles:

Especially useful when working with APIs or databases, you can use ternaries to assign default values if a certain value is undefined:

In the real world, the ternary operator serves as a quick, readable, and effective tool to handle conditional logic. Its utility spans across different domains of programming, from web development to data processing, making it a valuable asset in a developer's toolkit.

To wrap things up, the ternary operator stands as a testament to JavaScript's flexibility and expressiveness. By understanding its depth and potential, developers can craft cleaner, more efficient code. Embrace its simplicity and elegance for optimal coding experiences.

Let’s test your knowledge!

Which of the following statements about the ternary operator is false?

Continue learning with these javasript guides.

  • Getting Acquainted With JavaScript Sleep Functions
  • What Every Developer Should Know About JavaScript Boolean
  • JavaScript Object Iteration: How To Iterate Through An Object In Detail
  • How To Comment In JavaScript: Essential Techniques And Best Practices
  • A Deep Dive Into The World Of JavaScript Dictionary Functions

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

Unary, Binary, and Ternary Operators in JavaScript – Explained with Examples

Dillion Megida

There are many operators in JavaScript that let you carry out different operations.

These operators can be categorized based on the number of operands they require, and I'll be using examples to explain these categories in this tutorial.

The three categories of operators based on the number of operands they require are:

  • Unary operators: which require one operand (Un)
  • Binary operators: which require two operands (Bi)
  • Ternary operators: which require three operands (Ter)

Note that these categories do not only apply to JavaScript. They apply to programming in general.

In the rest of this article, I will share some examples of operators that fall under each category.

I have a video version of this topic you can watch if you're interested.

What is an Operand?

First, let's understand what an operand is. In an operation, an operand is the data that is being operated on . The operand combined with the operator makes an operation.

Look at this example:

Here we have a sum operation (which we will learn more about later). This operation involves the plus operator + , and there are two operands here: 20 and 30 .

Now that we understand operands, let's see examples of operators and the categories they fall under.

What is a Unary Operator?

These operators require one operand for operation. Providing two or more can result in a syntax error. Here are some examples of operators that fall under this category.

the typeof operator

The typeof operator returns the data type of a value. It requires only one operand. Here's an example:

If you pass two operands to it, you'd get an error:

The delete operator

You can use the delete operator to delete an item in an array or delete a property in an object. It's a unary operator that requires only one operand. Here's an example with an array:

Note that deleting items from an array with the delete operator is not the right way to do this. I explained why in this article here

And here's an example with an object:

The Unary plus + operator

This operator is not to be confused with the arithmetic plus operator which I will explain later in this article. The unary plus operator attempts to convert a non-number value to a number. It returns NaN where impossible. Here's an example:

As you can see here again, only one operand is required, which comes after the operator.

I'll stop with these three examples. But know that there are more unary operators such as the increment ++ , decrement ++ , and Logical NOT ! operators, to name a few.

What is a Binary Operator?

These operators require two operands for operation. If one or more than two operands are provided, such operators result in a syntax error.

Let's look at some operators that fall under this category

Arithmetic Operators

All arithmetic operators are binary operators. You have the first operand on the left of the operator, and the second operand on the right of the operator. Here are some examples:

If you don't provide two operands, you will get a syntax error. For example:

Comparison Operators

All comparison operators also require two operands. Here are some examples:

Assignment Operator =

The assignment operator is also a binary operator as it requires two operands. For example:

On the left, you have the first operand, the variable ( const number ), and on the right, you have the second operand, the value ( 20 ).

You're probably asking: "isn't const number two operands?". Well, const and number makes up one operand. The reason for this is const defines the behavior of number . The assignment operator = does not need const . So you can actually use the operator like this:

But it's good practice to always use a variable keyword.

So like I said, think of const number as one operand, and the value on the right as the second operand.

What is a Ternary Operator?

These operators require three operands. In JavaScript, there is one operator that falls under this category – the conditional operator. In other languages, perhaps, there could be more examples.

The Conditional Operator ? ... :

The conditional operator requires three operands:

  • the conditional expression
  • the truthy expression which gets evaluated if the condition is true
  • the falsy expression which gets evaluated if the condition is false .

You can learn more about the Conditional Operator here

Here's an example of how it works:

The first operand – the conditional expression – is score > 50 .

The second operand – the truthy expression – is "Good", which will be returned to the variable scoreRating if the condition is true .

The third operand – the falsy expression – is "Poor", which will be returned to the variable scoreRating if the condition is false .

I've written an article related to this operator that you can check out here . It's about why a ternary operator is not a conditional operator in JavaScript.

Operations in JavaScript involve one or more operands and an operator. And operators can be categorized based on the number of operands they require.

In this article, we've looked at the three categories of operators: unary , binary , and ternary . We also looked at the examples of operators in JavaScript that fall under each category.

Please share this article if you find it helpful.

Developer Advocate and Content Creator passionate about sharing my knowledge on Tech. I simplify JavaScript / ReactJS / NodeJS / Frameworks / TypeScript / et al My YT channel: youtube.com/c/deeecode

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

Learn C++ practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c++ interactively, c++ introduction.

  • C++ Variables and Literals
  • C++ Data Types
  • C++ Basic I/O
  • C++ Type Conversion

C++ Operators

  • C++ Comments

C++ Flow Control

  • C++ if...else
  • C++ for Loop
  • C++ do...while Loop
  • C++ continue
  • C++ switch Statement
  • C++ goto Statement
  • C++ Functions
  • C++ Function Types
  • C++ Function Overloading
  • C++ Default Argument
  • C++ Storage Class
  • C++ Recursion
  • C++ Return Reference

C++ Arrays & String

  • Multidimensional Arrays
  • C++ Function and Array
  • C++ Structures
  • Structure and Function
  • C++ Pointers to Structure
  • C++ Enumeration

C++ Object & Class

  • C++ Objects and Class
  • C++ Constructors
  • C++ Objects & Function

C++ Operator Overloading

  • C++ Pointers
  • C++ Pointers and Arrays
  • C++ Pointers and Functions
  • C++ Memory Management
  • C++ Inheritance
  • Inheritance Access Control
  • C++ Function Overriding
  • Inheritance Types
  • C++ Friend Function
  • C++ Virtual Function
  • C++ Templates

C++ Tutorials

C++ if, if...else and Nested if...else

  • Add Complex Numbers by Passing Structure to a Function
  • Check Whether Number is Even or Odd
  • Subtract Complex Number Using Operator Overloading

C++ Operator Precedence and Associativity

C++ Ternary Operator

In C++, the ternary operator is a concise, inline method used to execute one of two expressions based on a condition. It is also called the conditional operator.

  • Ternary Operator in C++

A ternary operator evaluates the test condition and executes an expression out of two based on the result of the condition.

Here, condition is evaluated and

  • if condition is true , expression1 is executed.
  • if condition is false , expression2 is executed.

The ternary operator takes 3 operands ( condition , expression1 and expression2 ). Hence, the name ternary operator .

  • Example: C++ Ternary Operator

Suppose the user enters 80 . Then, the condition marks >= 40 evaluates to true . Hence, the first expression "passed" is assigned to result .

Now, suppose the user enters 39.5 . Then, the condition marks >= 40 evaluates to false . Hence, the second expression "failed" is assigned to result .

Note: We should only use the ternary operator if the resulting statement is short.

1. Ternary Operator for Concise Code

The ternary operator is best for simple, inline conditional assignments where readability is not compromised. For example,

In this example, the condition age >= 18 is evaluated. If it's true, Adult is assigned to status; if it's false, Minor is assigned.

This is much more concise than using a full if...else statement, which would look like this:

Here, the if...else statement takes up more lines and can clutter code when used for many simple conditional assignments.

2. if...else for Clarity in Complex Conditions

The if...else statement is better suited for complex decision-making processes and when clarity and readability are prioritized over brevity.

Suppose you need to categorize weather based on multiple conditions. Using a ternary operator with multiple conditional statements would be cumbersome and hard to read. In such cases, we use if...else .

Let's look at an example.

3. Ternary Operator Implicitly Returns a Value

Let's look at an example to justify this point.

Here, the ternary operator returns the value based on the condition (number>0) . The returned value is stored in the result variable.

In contrast, if...else does not inherently return a value. Thus, assignment to a variable is explicit.

  • Nested Ternary Operators

It is also possible to use one ternary operator inside another ternary operator. It is called the nested ternary operator in C++.

Here's a program to find whether a number is positive, negative, or zero using the nested ternary operator.

In the above example, notice the use of ternary operators,

  • (number == 0) is the first test condition that checks if number is 0 or not. If it is, then it assigns the string value "Zero" to result .
  • Else, the second test condition (number > 0) is evaluated if the first condition is false .

Note : It is not recommended to use nested ternary operators. This is because it makes our code more complex.

Table of Contents

  • Introduction

Sorry about that.

Related Tutorials

C++ Tutorial

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

?: operator - the ternary conditional operator

  • 11 contributors

The conditional operator ?: , also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false , as the following example shows:

As the preceding example shows, the syntax for the conditional operator is as follows:

The condition expression must evaluate to true or false . If condition evaluates to true , the consequent expression is evaluated, and its result becomes the result of the operation. If condition evaluates to false , the alternative expression is evaluated, and its result becomes the result of the operation. Only consequent or alternative is evaluated. Conditional expressions are target-typed. That is, if a target type of a conditional expression is known, the types of consequent and alternative must be implicitly convertible to the target type, as the following example shows:

If a target type of a conditional expression is unknown (for example, when you use the var keyword) or the type of consequent and alternative must be the same or there must be an implicit conversion from one type to the other:

The conditional operator is right-associative, that is, an expression of the form

is evaluated as

You can use the following mnemonic device to remember how the conditional operator is evaluated:

Conditional ref expression

A conditional ref expression conditionally returns a variable reference, as the following example shows:

You can ref assign the result of a conditional ref expression, use it as a reference return or pass it as a ref , out , in , or ref readonly method parameter . You can also assign to the result of a conditional ref expression, as the preceding example shows.

The syntax for a conditional ref expression is as follows:

Like the conditional operator, a conditional ref expression evaluates only one of the two expressions: either consequent or alternative .

In a conditional ref expression, the type of consequent and alternative must be the same. Conditional ref expressions aren't target-typed.

Conditional operator and an if statement

Use of the conditional operator instead of an if statement might result in more concise code in cases when you need conditionally to compute a value. The following example demonstrates two ways to classify an integer as negative or nonnegative:

Operator overloadability

A user-defined type can't overload the conditional operator.

C# language specification

For more information, see the Conditional operator section of the C# language specification .

Specifications for newer features are:

  • Target-typed conditional expression
  • Simplify conditional expression (style rule IDE0075)
  • C# operators and expressions
  • if statement
  • ?. and ?[] operators
  • ?? and ??= operators
  • ref keyword

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Download and Install Python 3 Latest Version
  • Statement, Indentation and Comment in Python
  • Python | Set 2 (Variables, Expressions, Conditions and Functions)
  • Global and Local Variables in Python
  • Type Conversion in Python
  • Private Variables in Python
  • __name__ (A Special variable) in Python
  • Taking input in Python
  • Taking multiple inputs from user in Python
  • Python | Output using print() function
  • Python end parameter in print()
  • Python | Output Formatting
  • Python Operators

Ternary Operator in Python

  • Operator Overloading in Python
  • Python | a += b is not always a = a + b
  • Difference between == and is operator in Python
  • Python | Set 3 (Strings, Lists, Tuples, Iterations)
  • Python String
  • Python Lists
  • Python Tuples
  • Python Sets
  • Dictionaries in Python
  • Python Arrays
  • Python If Else Statements - Conditional Statements

In this article, you’ll learn how to use the ternary operator in Python. The ternary operator in Python is simply a shorter way of writing an if and if…else statement. We’ll see its syntax along with some practical examples.

Python Ternary Operator and its Benefits

The Python ternary operator determines if a condition is true or false and then returns the appropriate value in accordance with the result. The ternary operator is useful in cases where we need to assign a value to a variable based on a simple condition, and we want to keep our code more concise — all in just one line of code. It’s particularly handy when you want to avoid writing multiple lines for a simple if-else situation.

Syntax of Ternary Operator in Python

Syntax : [on_true] if [expression] else [on_false] expression : conditional_expression | lambda_expr

Simple Method to Use Ternary Operator

In this example, we are comparing and finding the minimum number by using the ternary operator. The expression min is used to print a or b based on the given condition. For example, if a is less than b then the output is a, if a is not less than b then the output is b.

Ternary Operator Examples

Here we will see the different example to use Python Ternary Operator:

Ternary Operator in Python If-Else

Python ternary operator using tuples, python ternary operator using dictionary, python ternary operator using lambda, print in if ternary operator, limitations of python ternary operator.

Example: Using Native way

Python program to demonstrate nested ternary operator. In this example, we have used simple if-else without using ternary operator.

Example: Using Ternary Operator

In this example, we are using a nested if-else to demonstrate ternary operator. If a and b are equal then we will print a and b are equal and else if a>b then we will print a is greater than b otherwise b is greater than a.

In this example, we are using tuple s to demonstrate ternary operator. We are using tuple for selecting an item and if [a<b] is true it return 1, so element with 1 index will print else if [a<b] is false it return 0, so element with 0 index will print.

In this example, we are using Dictionary to demonstrate ternary operator. We are using tuple for selecting an item and if [a<b] is true it return 1, so element with 1 index will print else if [a<b] is false it return 0, so element with 0 index will print.

In this example, we are using Lambda to demonstrate ternary operator. We are using tuple for selecting an item and if [a<b] is true it return 1, so element with 1 index will print else if [a<b] is false it return 0, so element with 0 index will print.

In this example, we are finding the larger number among two numbers using ternary operator in python3.

Python ternary is used to write concise conditional statements but it too have some limitations.

  • Readability: T ernary operator can make simple conditional expressions more concise, it can also reduce the readability of your code, especially if the condition and the expressions are complex.
  • Potential for Error : Incorrect placement of parentheses, missing colons, or incorrect order of expressions can lead to syntax errors that might be harder to spot.
  • Debugging : When debugging, it might be harder to inspect the values of variables involved in a complex ternary expression.
  • Maintenance and Extensibility : Complex ternary expressions might become harder to maintain and extend especially when the codebase grows.
  • Can’t use assignment statements: Each operand of the Python ternary operator is an  expression , not a statement, that means we can’t use assignment statements inside any of them. Otherwise, the program will throw an error.

Please Login to comment...

Similar reads.

  • What are Tiktok AI Avatars?
  • Poe Introduces A Price-per-message Revenue Model For AI Bot Creators
  • Truecaller For Web Now Available For Android Users In India
  • Google Introduces New AI-powered Vids App
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Java Ternary Operator with Examples

    assignment with ternary operator

  2. 10 Examples Of Ternary Operator In Java

    assignment with ternary operator

  3. Java Ternary Operator with Examples

    assignment with ternary operator

  4. Ternary Operator

    assignment with ternary operator

  5. C Ternary Operator (With Examples)

    assignment with ternary operator

  6. Ternary Operator in Java

    assignment with ternary operator

VIDEO

  1. 10. Ternary Operator for EvenOdd Checking in JavaScript

  2. Ternary Operator in C Print Absolute Numbers

  3. Ternary Operator #coding #javascript

  4. ternary operator

  5. Ternary Operators in C Lec-94|C Programming Tutorial in Hindi

  6. es6 Ternary Operator

COMMENTS

  1. Conditional (ternary) operator

    The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if ...

  2. How do I use the conditional (ternary) operator?

    It's most commonly used in assignment operations, although it has other uses as well. The ternary operator ? is a way of shortening an if-else clause, and is also called an immediate-if statement in other languages ( IIf(condition,true-clause,false-clause) in VB, for example). For example: bool Three = SOME_VALUE;

  3. Quick Tip: How to Use the Ternary Operator in JavaScript

    Using the Ternary Operator for Value Assignment. 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 ...

  4. How to Use the Ternary Operator in JavaScript

    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 ...

  5. Ternary conditional operator

    In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. ... Bear in mind also that some types allow initialization, but do not allow assignment, or even that the assignment operator and the constructor do totally different ...

  6. Unraveling The JavaScript Ternary Operator: An In-Depth Guide For

    The ternary operator in JavaScript provides a concise way to execute code based on a boolean condition, replacing traditional if-else statements. It consists of three parts: a condition, a result upon true (then), and a result upon false (else), making code more readable for simple conditions. While useful for simple, inline conditional logic ...

  7. Python Ternary: How to Use It and Why It's Useful (with Examples)

    While the ternary operator is a way of re-writing a classic if-else block, in a certain sense, it behaves like a function since it returns a value. Indeed, we can assign the result of this operation to a variable: my_var = a if condition else b. For example: x = "Is true" if True else "Is false" print(x) Is true.

  8. Learn JavaScript Operators

    Conclusion. In this tutorial, you've learned the 7 types of JavaScript operators: Arithmetic, assignment, comparison, logical, ternary, typeof, and bitwise operators. These operators can be used to manipulate values and variables to achieve a desired outcome. Congratulations on finishing this guide!

  9. Ternary Operator in Programming

    The ternary operator is a conditional operator that takes three operands: a condition, a value to be returned if the condition is true, and a value to be returned if the condition is false. It evaluates the condition and returns one of the two specified values based on whether the condition is true or false. Syntax of Ternary Operator: The ...

  10. c

    It seems slightly dubious doing only one assignment (why is control-D assigned to whatever this expression is assigned to), but it's hard to know without more code than is shown. It the expression is not assigned or otherwise used, then using the ternary operator is wholly inappropriate — use an if statement. - Jonathan Leffler.

  11. Unary, Binary, and Ternary Operators in JavaScript

    Here's an example: +"200" // 20 - number +false // 0 - number representation +"hello" // NaN. As you can see here again, only one operand is required, which comes after the operator. I'll stop with these three examples. But know that there are more unary operators such as the increment ++, decrement ++, and Logical NOT ! operators, to name a few.

  12. C Ternary Operator (With Examples)

    Syntax of Ternary Operator. The syntax of ternary operator is : testCondition ? expression1 : expression 2; The testCondition is a boolean expression that results in either true or false.If the condition is . true - expression1 (before the colon) is executed; false - expression2 (after the colon) is executed; The ternary operator takes 3 operands (condition, expression1 and expression2).

  13. Java Ternary Operator with Examples

    Assignment Operator; Relational Operators; Logical Operators; ... Java ternary operator is the only conditional operator that takes three operands. It's a one-liner replacement for the if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using ...

  14. JavaScript Ternary Operator

    JavaScript Ternary Operator. JavaScript Ternary Operator (Conditional Operator) is a concise way to write a conditional (if-else) statement. Ternary Operator takes three operands i.e. condition, true value and false value. In this article, we are going to learn about Ternary Operator.

  15. C++ Ternary Operator (With Examples)

    Ternary Operator in C++. A ternary operator evaluates the test condition and executes an expression out of two based on the result of the condition. Syntax. condition ? expression1 : expression2; Here, condition is evaluated and. if condition is true, expression1 is executed. if condition is false, expression2 is executed.

  16. Assignment to expression using ternary operator

    2,665 2 21 23. 1. Because the right side of the assignment contains a complex expression, the lambda expression on the right cannot be resolved to a type. In order to make the expression compile, you have to give the compiler actual type information: Expression<Func<Foo, bool>> filterExpression = id.HasValue ?

  17. ?: operator

    The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false, as the following example shows: string GetWeatherDisplay(double tempInCelsius) => tempInCelsius < 20.0 ?

  18. How to Use the Ternary Conditional Operator in Bash

    $ a=1; b=2; c=3 $ echo $(( max = a > b ? ( a > c ? a : c) : (b > c ? b : c) )) 3. In this case, the second and third operands or the main ternary expression are themselves ternary expressions.If a is greater than b, then a is compared to c and the larger of the two is returned. Otherwise, b is compared to c and the larger is returned. Numerically, since the first operand evaluates to zero ...

  19. The ternary (conditional) operator in C

    the ternary operator is slower than if/else statement on my machine! so according to different compiler optimization techniques, ternal operator and if/else may behaves much different. ... Assignment in ternary operator. Hot Network Questions Why does a 1:1 transformer preserve voltage? Op-amp (LM348N) becomes very hot when connected to power ...

  20. Ternary conditional and assignment operator precedence

    The operator precedence in the C/C++ language in not defined by a table or numbers, but by a grammar. Here is the grammar for conditional operator from C++0x draft chapter 5.16 Conditional operator [expr.cond]:. conditional-expression: logical-or-expression logical-or-expression ? expression : assignment-expression

  21. Ternary Operator in Python

    In this example, we are comparing and finding the minimum number by using the ternary operator. The expression min is used to print a or b based on the given condition. For example, if a is less than b then the output is a, if a is not less than b then the output is b. Python3. a, b = 10, 20. # Copy value of a in min if a < b else copy b.