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

JavaScript Ternary Operator – Syntax and Example Use Case

Dillion Megida

There are many operators in JavaScript, one of which is the ternary operator. In this article, I'll explain what this operator is, and how it can be useful when building applications.

I have a video version of this topic you can check out as well to supplement your learning.

What is the Ternary Operator?

The ternary operator is a conditional operator which evaluates either of two expressions – a true expression and a false expression – based on a conditional expression that you provide.

Here's the syntax:

You have the condition which returns a truthy or falsy value. Truthy values here include true , and non-falsy values. Falsy values here include false , null , 0 , and so on.

After the condition, you have the question mark (which you can think of as "questioning the condition"), followed by the trueExpression . This expression is executed if the condition expression evaluates to true .

After the true expression, you have a colon, followed by the falseExpression . This expression is executed if the condition expression evaluates to false .

The ternary operator returns a value that you can assign to a variable. You cannot use the operator without assigning the returned value to a variable:

The returned value depends on the evaluation of the condition expression. If the condition is true , the returned value returned from trueExpression is assigned to the variable. Else, the returned value from falseExpression will be assigned to the variable.

How to Use the Ternary Operator in Place of if Statements

The ternary operator can be a good replacement for if statements in some cases. It allows you to write concise, cleaner, and easier-to-read lines of code if used well.

Let's see an example:

In this example, we have a score variable with 80 and a scoreRating variable. Then we have an if statement that checks score > 70 . If this condition evaluates to true , the scoreRating variable is assigned "Excellent" , else, it is assigned "Do better" .

We can improve this code with the ternary operator. Here's how.

Remember the syntax: you have the condition, a question mark, the true expression, a colon, and finally a false expression. Let's look at this in code:

This is how we use the ternary operator. The true and false expressions here are strings that will be returned to the scoreRating variable depending on our condition score > 70 .

The true and false expressions can be any kind of expression from function executions to arithmetic operations and so on. Here's an example with a function execution:

Here, you see that as the condition returns false , the false expression, printPoor() is executed which prints "Poor result" to the console. And as the false expression returns "poor", you can see that value assigned to the result variable.

For the rest of this article, I'll be using string true and false expressions for simplicity.

How to Use Nested Ternary Operators

What if you wanted to achieve an if...else if...else statement with a ternary operator? Then you can use nested ternary operators. You should be careful how you use this, however, as it can make your code harder to read.

We have an if-else-if-else statement here where we first check if score > 70 . If this returns true , we assign "Excellent" to the scoreRating variable. If this returns false , we check if score > 50 . If this second condition returns true , we assign "Average" to the variable but if this also returns false, we finally ( else ) assign "Do better" to the variable.

Let's see how to do this with the ternary operator:

Here, you see we have two question marks and two colons. In the first ternary operator, we have the conditional expression score > 70 . After the first question mark, we have the true expression which is "Excellent" . After the first colon, the next expression is supposed to be the false expression. For the false expression, we declare another conditional expression using the ternary operator.

The second condition here is score > 70 . After the second question mark, we have the true expression which is "Average" . After the second colon, we now have another false expression, which is "Do better" .

With this, if the first condition is true, "Excellent" is returned to scoreRating . If the first condition is false, then we have another condition check. If this second condition is true, "Average" is returned to the variable. If this second condition is also false, then we have the final false expression, "Do better", which will be assigned to the variable.

Multiple Ternary Operators Can Make Your Code Unreadable

In the previous examples, we've seen how we can improve our code while maintaining readability. But you have to be careful when using multiple ternary operators.

Imagine we had an extra ternary operator in our previous example:

Here we have three ternary operators, and you can see that things are becoming harder to read.

In cases like this where you need multiple conditions, using an if or switch statement, though requiring longer lines of code, makes you write more readable code.

Wrapping Up

The ternary operator allows you to evaluate conditional expressions and can substitute for if statements in some cases. It allows you to write shorter and cleaner code (even on one line).

In this article, I've shown you how it works, using some if examples and the ternary operator version. I also emphasized that you should be careful when using nested ternary operators as that can then make your code unreadable.

If you enjoyed this piece, please share!

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

Home » JavaScript Tutorial » JavaScript Ternary Operator

JavaScript Ternary Operator

javascript ternary operator

Summary : in this tutorial, you will learn how to use the JavaScript ternary operator to make your code more concise.  

Introduction to JavaScript ternary operator

When you want to execute a block if a condition evaluates to true , you often use an if…else statement. For example:

In this example, we show a message that a person can drive if the age is greater than or equal to 16. Alternatively, you can use a ternary operator instead of the if-else statement like this:

Or you can use the ternary operator in an expression as follows:

Here’s the syntax of the ternary operator:

In this syntax, the condition is an expression that evaluates to a Boolean value, either true or false .

If the condition is true , the first expression ( expresionIfTrue ) executes. If it is false, the second expression ( expressionIfFalse ) executes.

The following shows the syntax of the ternary operator used in an expression:

In this syntax, if the condition is true , the variableName will take the result of the first expression ( expressionIfTrue ) or expressionIfFalse otherwise.

JavaScript ternary operator examples

Let’s take some examples of using the ternary operator.

1) Using the JavaScript ternary operator to perform multiple statements

The following example uses the ternary operator to perform multiple operations, where each operation is separated by a comma. For example:

In this example, the returned value of the ternary operator is the last value in the comma-separated list.

2) Simplifying ternary operator example

See the following example:

If the locked is 1, then the canChange variable is set to false , otherwise, it is set to true . In this case, you can simplify it by using a Boolean expression as follows:

3) Using multiple JavaScript ternary operators example

The following example shows how to use two ternary operators in the same expression:

It’s a good practice to use the ternary operator when it makes the code easier to read. If the logic contains many if...else statements, you should avoid using the ternary operators.

  • Use the JavaScript ternary operator ( ?: )to make the code more concise.

refine App screenshot

Struggling with internal tools?

Explore refine’s limitless possibilities in crafting CRUD apps, CRM solutions, HR dashboards, and more!

How to Use the JavaScript Ternary Operator

How to Use the JavaScript Ternary Operator

This article was last updated on January 24, 2024 to add more detailed information and implementation of JavaScript Ternary Operator

Introduction ​

This post is about the Ternary Operator in JavaScript. We discuss what the ternary operator is and how it works. We go over some examples demonstrating when and why to use it and how it compares to other JavaScript control structures like if/else , if/else if/else and switch . We also learn about some of the best practices while using JS Ternary Operator.

Steps we'll cover:

  • What is JavaScript Ternary Operator ?
  • What are Truthy/Falsy Values ?
  • JavaScript Ternary Operator: A Shorthand for if/else
  • Using the JavaScript Ternary Operator to Test a Function's Truthiness
  • Handling Nullish Values with JS Ternary Operator
  • JavaScript Ternary Operator: When The Return Value Rules
  • Chaining Ternary Operators in JavaScript
  • JavaScript Ternary Operator Best Practices

What is JavaScript Ternary Operator ? ​

The Ternary Operator in JavaScript is a conditional control structure that checks for the return value of an expression and executes a block of code based on whether the value is truthy or falsy. It then returns the return value of the executed block.

The JavaScript Ternary Operator is also referred to as the Conditional Operator.

How JS Ternary Operator Works ​

The Ternary Operator in JavaScript is denoted by the question mark: ? . It is called so because it takes three operands:

  • The conditional expression that returns either true or false based on a check that evaluates to either truthy or falsy .
  • The block of code which should be executed if the conditional check returns true .
  • The block that should run if it returns false .

The syntax for the JavaScript Ternary Operator looks like this:

As we can see, the Ternary Operator places the conditional expression before the ? and accepts the executable expressions as two other operands that are separated by a colon, : .

If the conditionalExpression evaluates to a truthy value, exprIfTruthy is executed. If it evaluates to a falsy value, exprIfFalsy is executed.

What are Truthy/Falsy Values ? ​

In JavaScript, a truthy value corresponds to a value that is considered equivalent to true had that been converted to a Boolean. This is another way of saying "this thing exists". All values in JavaScript are truthy if they do not evaluate to or are not defined to be falsy .

A falsy value is a value that is casted as false when it is converted to a Boolean. In JavaScript, the following values are coerced / converted to false :

false , 0 , -0 , 0n "" , null , undefined , NaN and document.all .

Expressions that evaluate to anything other than these are considered truthy .

When to Use the JS Ternary Operator ? ​

We use the JavaScript Ternary Operator when we need to control execution flow between two paths based on a conditional check that returns a Boolean.

A simplest example involves testing the value of an expression stored in a variable to see whether it exists or not, and then pursue an execution path based on the outcome. If it exists, we do relevant stuff and return it; if not, do some other relevant stuff and return that. The below code shows how:

In the above snippet, student ? tests to see if student is truthy. The value from this conditional test is used to decide the value of the stored variable, welcomeStudent . In other words, we are using the conditional operator to control the value of welcomeStudent based on the value of student .

Notice that the return value of the executed block following the check is returned as the operator's return value. That allow us to store it in welcomeStudent .

JavaScript Ternary Operator: A Shorthand for if/else ​

The Ternary Operator is a concise alternative to if/else . For example, we could have written the above control flow like this:

Notice how the ternary operator used previously helped avoid using the above procedural if/else flow. The Ternary Operator made the code more readable, reusable and the logic easier to follow.

Using the JavaScript Ternary Operator to Test a Function's Truthiness ​

The ternary operator can also be used when we need to test the return a value of a function. As in the welcomeStudentTernary function below:

Again, it provides conciseness. And goes well with arrow functions.

Handling Nullish Values with JS Ternary Operator ​

Notice how the nullish arguments are being considered in both cases. With just a few characters added, the Ternary one-liner offers more convenience to an efficient developer who doesn't want to waste lines for dealing with nullish logic.

JavaScript Ternary Operator: When The Return Value Rules ​

It is important to notice that with the Ternary Operator, we are only interested in the return value of the conditional check as well as those of the two execution blocks. Side effects are less important.

For example, the Ternary Operator would not be useful for us had being polite or yelling was important to us:

In the case when they are more important, we should be using if/else statements, as in welcomeStudent . So, the JavaScript Ternary Operator is useful in cases when the return value of the expressions matter more. This is a major distinction between the usage of if/else and the Ternary operator in JavaScript.

Chaining Ternary Operators in JavaScript ​

We can chain ternary operators to emulate a if/else if/else control structure or a switch statement:

Here, we chained an additional conditional operator into the third operand at each level.

JavaScript Ternary Operator Best Practices ​

Many developers do not prefer chained ternary operators like the one above because multiple conditional checks hurt readability and maintainability. Instead of chaining ternary operators, using plain if/else if/else or switch statements are recommended when there are multiple paths in a control flow.

So, here are some best practices:

  • Use the JavaScript Ternary Operator when there are only two paths in the control flow.
  • Use the JS Ternary Operator consistently.
  • Avoid using chained Ternary Operators as they make the code difficult to read and maintain.
  • Use a JavaScript Ternary Operator with arrow functions as they also produce good one-liners.
  • In the case complex conditional checks are involved, use parentheses to properly implement the logic. This also improves readability and maintainability

In this post, we expounded on the use of the Ternary Operator in JavaScript. We acknowledged its importance in writing concise code, especially in situations that involve a conditional check and two execution paths.

We saw with examples that the JS Ternary Operator is a good alternative to if/else and is preferable when the return values of the expressions matter more than side effects. We covered a case where it is useful for storing the value returned from evaluating primitives across the execution path as well as one where the same is done after executing a function.

We also encountered an example that shows JavaScript Ternary Operators can be chained to emulate if/else if/else and switch blocks, but the recommended way is to avoid chaining multiple Ternary Operators. We learned about other best practices such as using it consistently in situations where there are only two paths in the control flow, with arrow functions and with parentheses when needed.

Description

Specifications, browser compatibility.

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

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

A simple example:

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:

  • if statement

Document Tags and Contributors

  • Conditional
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Using promises
  • Iterators and generators
  • Meta programming
  • JavaScript modules
  • Client-side web APIs
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.ListFormat
  • Intl.Locale
  • Intl.NumberFormat
  • Intl.PluralRules
  • Intl.RelativeTimeFormat
  • ReferenceError
  • SharedArrayBuffer
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Assignment operators
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical operators
  • Object initializer
  • Operator precedence
  • (currently at stage 1) pipes the value of an expression into a function. This allows the creation of chained function calls in a readable manner. The result is syntactic sugar in which a function call with a single argument can be written like this:">Pipeline operator
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for await...of
  • for each...in
  • function declaration
  • import.meta
  • try...catch
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • The arguments object
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: can't access lexical declaration`X' before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: 'x' is not iterable
  • TypeError: More arguments needed
  • TypeError: Reduce of empty array with no initial value
  • TypeError: can't access dead object
  • TypeError: can't access property "x" of "y"
  • TypeError: can't assign to property "x" on "y": not an object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cannot use 'in' operator to search for 'x' in 'y'
  • TypeError: cyclic object value
  • TypeError: invalid 'instanceof' operand 'x'
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • X.prototype.y called on incompatible type
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

Learn the best of web development

Get the latest and greatest from MDN delivered straight to your inbox.

Thanks! Please check your inbox to confirm your subscription.

If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us.

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types

JavaScript Operators

  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript if...else Statement

JavaScript Comparison and Logical Operators

JavaScript null and undefined

  • JavaScript typeof Operator
  • JavaScript while and do...while Loop

JavaScript Ternary Operator

A ternary operator can be used to replace an  if..else statement in certain situations. Before you learn about ternary operators, be sure to check the JavaScript if...else tutorial .

  • What is a Ternary operator?

A ternary operator evaluates a condition and executes a block of code based on the condition.

Its syntax is:

The ternary operator evaluates the test condition.

  • If the condition is true , expression1 is executed.
  • If the condition is false , expression2 is executed.

The ternary operator takes three operands, hence, the name ternary operator. It is also known as a conditional operator.

Let's write a program to determine if a student passed or failed in the exam based on marks obtained.

Example: JavaScript Ternary Operator

Suppose the user enters 78 . Then the condition marks >= 40 is checked which evaluates to true . So the first expression pass is assigned to the result variable.

Suppose the use enters 35 . Then the condition marks >= 40 evaluates to false . So the second expression fail is assigned to the result variable.

Ternary Operator Used Instead of if...else

In JavaScript, a ternary operator can be used to replace certain types of if..else statements. For example,

You can replace this code

The output of both programs will be the same.

  • Nested ternary operators

You can also nest one ternary operator as an expression inside another ternary operator. For example,

Note : You should try to avoid nested ternary operators whenever possible as they make your code hard to read.

Table of Contents

  • Ternary operator used instead if...else

Video: JavaScript Ternary Operators

Sorry about that.

Related Tutorials

JavaScript Tutorial

js ternary without assignment

Hiring? Flexiple helps you build your dream team of  developers   and  designers .

JavaScript Ternary Operator – Syntax and Example Use Case

Harsh Pandey

Harsh Pandey

Last updated on 16 Apr 2024

The JavaScript Ternary Operator introduces a concise way to execute conditional logic in JavaScript code. Known as the conditional operator, it serves as a compact alternative to the if-else statement, enabling developers to write cleaner, more readable code. It operates on three operands: a condition, a value if the condition is true, and a value if the condition is false, structured as condition ? valueIfTrue : valueIfFalse . This operator shines in situations requiring simple decisions and assignments based on a condition. Its syntax and usage are straightforward, making it a favorite tool for optimizing code brevity and clarity.

What is the Ternary Operator?

The Ternary Operator in JavaScript is a conditional operator that facilitates the execution of code based on a ternary (three-part) condition. It is represented by the syntax condition ? expressionIfTrue : expressionIfFalse , making it the only operator in JavaScript that takes three operands. This operator evaluates the condition: if the condition is true, it returns the value of expressionIfTrue ; if false, it returns the value of expressionIfFalse .

For example:

In this case, the condition 5 > 3 is true, so the operator returns "Yes". The Ternary Operator streamlines decision-making in code, allowing for more compact expressions than traditional if-else statements. It is ideal for simple conditional assignments and inline conditions.

Syntax Description

The syntax of the JavaScript Ternary Operator consists of three parts: a condition, an expression to execute if the condition is true, and an expression to execute if the condition is false. This is represented as condition ? expressionIfTrue : expressionIfFalse . The operator first evaluates the condition. If the condition is truthy, it executes and returns the value of expressionIfTrue . If the condition is falsy, it executes and returns the value of expressionIfFalse .

For instance:

Here, the condition age >= 18 evaluates to true, thus the ternary operator returns "Eligible to vote". This succinct syntax makes the ternary operator ideal for quick conditional checks and assignments within JavaScript code, promoting readability and reducing the need for more verbose if-else statements.

Ternary Operator Used Instead of if...else

The Ternary Operator can be used instead of if...else statements to streamline conditional logic in JavaScript. It excels in scenarios where a simple condition needs to determine one of two values or actions. The ternary operator's compact form allows for inline conditional evaluations and assignments, reducing the complexity and length of code compared to traditional if...else constructs.

For example, using if...else:

The same logic with the ternary operator:

This example demonstrates how the ternary operator condenses multiple lines of an if...else statement into a single, readable line. It's particularly useful for assignments and return statements where the goal is to choose between one of two values based on a condition.

How to Use Nested Ternary Operators

To use nested ternary operators in JavaScript, one ternary operation is placed inside another, allowing for multiple conditions to be evaluated in a concise manner. This technique can handle complex logic within a single line of code, though it's crucial to maintain readability. Each nested ternary should follow the same syntax as a standard ternary operator: condition ? expressionIfTrue : expressionIfFalse .

In this example, multiple conditions determine the final grade based on a score. The first condition checks if the score is greater than or equal to 90, returning "A" if true. If false, it moves to the next condition, and so on, until a match is found or the last option is returned. While powerful, nested ternary operators should be used sparingly to avoid complicating the code. Clarity often trumps conciseness, especially when conditions become complex.

Multiple Ternary Operators Can Make Your Code Unreadable

Using multiple ternary operators in JavaScript can make your code unreadable due to the complexity and compactness of nested conditions. While the ternary operator is valuable for its brevity and inline conditional logic, overuse, especially with nesting, can lead to code that is difficult to understand at a glance. This decreases maintainability and can introduce bugs that are hard to trace.

In this snippet, the nested ternary operators evaluate the speed and return a message. While functional, deciphering the logic requires careful examination, contrasting with the clarity offered by more verbose conditional statements like if-else. It's advisable to limit the use of nested ternary operators and opt for alternatives that prioritize readability, especially in complex scenarios.

In conclusion, the JavaScript Ternary Operator offers a succinct and efficient way to perform conditional operations within your code. It stands out for its simplicity, allowing for quick decision-making between two possible outcomes based on a single condition. The ternary operator enhances code readability and maintainability, especially in situations where traditional if...else statements would introduce unnecessary complexity. However, when using nested ternary operators, it's essential to balance conciseness with clarity to ensure that your code remains accessible to others. Embracing the ternary operator can significantly streamline your JavaScript coding practices, provided it's applied judiciously and with consideration for fellow developers.

Work with top startups & companies. Get paid on time.

Try a top quality developer for 7 days. pay only if satisfied..

// Find jobs by category

You've got the vision, we help you create the best squad. Pick from our highly skilled lineup of the best independent engineers in the world.

  • Ruby on Rails
  • Elasticsearch
  • Google Cloud
  • React Native
  • Contact Details
  • 2093, Philadelphia Pike, DE 19703, Claymont
  • [email protected]
  • Explore jobs
  • We are Hiring!
  • Write for us
  • 2093, Philadelphia Pike DE 19703, Claymont

Copyright @ 2024 Flexiple Inc

DEV Community

DEV Community

Saulo Dias

Posted on Jul 1, 2021 • Updated on Mar 13

Ternary Operator: Better Alternatives

The ternary operator is a nice way to write concise value assignments without having to write a more lengthy if/else . For example:

However it's easy to misuse the ternary operator for things where simpler operators could often have been a better choice. So here are some alternatives for common mistakes.

Static true/false assignments:

Nullable assignment (falsy case).

Note: The code above will return null as long as test is falsy .

Nullable assignment (nullish case)

See: Nullish coalescing operator (??)

By the way...

Checking for undefined

I have seen this a few times. I promise.

See: Optional chaining (?.) [elvis operator]

Beware of browser coverage . If you want to use optional chaining safely, it might be a good idea to use TypeScript configured to transpile the code to ES5 with the modules configured to esnext, to use the latest ECMAScript features.

The ternary (but not actually ternary) operator

This is my favorite one, and also an honest mistake. Some people get overexcited with the simplicity of the ternary operator and might think it is just a "shorter" if/else statement.

The single-line if statement is simple and clean enough for that purpose, and we know test ? value = 8 will not work. The ternary operator needs to have an else return value. If you don't need it, use a single-line if .

Another variant

In React, sometimes when we want to render a component if a specific condition is true, we might see something like this.

I would only use a ternary operator for the example below in the case I want to render one component or another.

Wrapping up...

In a nutshell, if your ternary operator does not have a structure like the one below, you should raise an eyebrow and check if there really aren't other simpler alternatives.

Can you think of other examples you have seen of poor use of the ternary operator? Please let me know in the comments below.

Top comments (4)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

grahamthedev profile image

  • Location United Kingdown
  • Work DevRel - open to opportunities
  • Joined Jan 2, 2021
Great list, just be careful with Optional chaining, support is only around 90%.

Also what is "The ternary operator with disability" meant to be as I don't think that is a common term and as it reads it comes across as something that could be offensive.

I understand that could just be a language issue so I thought I would ask.

saulodias profile image

  • Location Rio de Janeiro, Brazil
  • Education Automation and Control Engineering at CEFET/RJ
  • Work Software Developer at Radix Engineering and Software
  • Joined Apr 29, 2021

Excellent observation.

I have edited out that bad attempt at humor. I'll try and keep my questionable sense of humor away from my posts. Sorry about that, and thanks for the feedback.

juniordevforlife profile image

  • Location Austin, TX
  • Education BS CIS
  • Work UI Developer
  • Joined Apr 6, 2020

I am guilty of using ternary operator when I could probably use something else. Great read, I'll work on incorporating these ideas.

encarvlucas profile image

  • Joined Jul 20, 2021

Great content!

Some comments have been hidden by the post's author - find out more

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

sachadee profile image

Encrypt/Decrypt Data between Python 3 and JavaScript (AES algorithm)

SachaDee - Apr 21

jamescroissant profile image

What React beginners should know about React 19 first.

Yu Hamada - Apr 21

gloriasilver profile image

Essential ES6 JavaScript Features Every JavaScript Developer Should Know

Tejuosho Gloria - May 1

ivordev profile image

Designing React Hooks for Flexibility

Ivor - Apr 23

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

How to Use the Ternary Operator in JavaScript

js ternary without assignment

Conditional statements allow programmers to control the execution of code based on logical conditions. Like many other programming languages, JavaScript features  if/else statements that achieve this goal.

What Is The Ternary (Conditional) Operator in JavaScript?

An alternative to the if/else statement, the ternary operator allows JavaScript developers to write concise conditional statements. It is written as “?:” and takes three operands; a logical condition, a value to return if true, and a value to return if false . 

But it’s common knowledge among developers that if/else statements with lots of conditions can get messy. They often make scripts unnecessarily long, difficult to debug, and hard to maintain. Fortunately, JavaScript’s ternary operator provides an alternative to the if/else statement, allowing for more concise and maintainable code.

In this article, we’ll write conditional statements with the ternary operator and learn to use it in different situations.

More From Rory Spanton Polynomial Regression: An Introduction

Writing a Simple Expression With the Ternary Operator 

The ternary operator gets its name by being the only operator in JavaScript that takes three operands, or parts. The first part of a ternary operation is a logical condition that returns a true or false value. Then, after a question mark , come two expressions, separated by a colon. The first is an expression to execute if the logical condition is true, while the second expression executes if the condition is false. The generic form of the function is below.

The ternary expression is an alternative to the conventional if/else statement. The if/else statement below is equivalent to the ternary operation above.

Because of its similarities to the if/else statement, using a simple ternary operation is straightforward. Let’s say we have a website where users can make an account. Once users sign in, we want to give them a custom greeting. We can create a basic function to do this using the ternary operator.

This function takes a condition called signedIn , which is a true or false value that relates to whether a user has logged into their account. If the condition is true, the ternary operator returns a personalized greeting. If the condition is false, it returns a generic greeting.

This is a neat way of writing simple logic. If we used an if/else statement instead of a ternary operation, the function would take up more space to achieve exactly the same result.

Evaluate Truthy/Falsy Conditions With Ternary Operator

Just like if/else statements in JavaScript, ternary expressions can evaluate truthy or falsy conditions. These conditions might return true or false values, but might also return other values that JavaScript coerces to be true or false. For example, if a condition returns null , NaN , 0 , an empty string ( “” ) or undefined , JavaScript will treat it as false in a ternary operation.

This behavior comes in handy when dealing with conditions that return missing values. We can use our custom greeting function from the previous example to show this. Giving this function a condition that returns null executes the “false” expression by default.

Although truthy and falsy conditions can be useful, they can also have unintended consequences. For example, we could assign a value of 1  or 0  to our condition signedIn . But a mistake in this assignment could result in signedIn having a NaN or undefined value. JavaScript would then treat the condition as false without any warning, which could lead to unexpected behavior.

To avoid situations like this, we can set conditions that test for exact values. If we only wanted to output a personalized greeting if signedIn has a value of 1 , we could write the following.

Using the Ternary Operator With Many Conditions

The ternary operator can also be an alternative to more complex if/else statements with several conditions. For example, we could check that members on our website are both signed in and have a paid membership before giving them a custom greeting. We can do this in a ternary operation by adding the extra condition using the && operator.

Again, this phrasing is more concise than an if/else statement. But we can go even further with the ternary operator by specifying multiple “else” conditions.

For instance, we could use the ternary operator to determine which stage of life a customer is in based on their age. If we wanted to classify users as children, teenagers, adults, or seniors, we could use the following function ternary operation:

Chaining together ternary operators like this saves plenty of space. Rewriting this function as a chain of if/else statements takes up around twice as many lines.

This is also an example where using if/else statements leads to less readable code. Although the ternary operator displays each condition and its corresponding return value in the same line, the if/else statement separates these pairings. This makes the logic of the if/else code harder to follow at a glance. If used within longer scripts, this might also make such code harder to debug, giving further reason to use the ternary operator.

Strengths and Limitations of the Ternary Operator

As seen above, the ternary operator in JavaScript has many strengths as an alternative to if/else statements.

Strengths of the Ternary Operator in JavaScript

  • It can represent conditional statements more concisely than if/else statements
  • In cases where conditions and return values are simple, ternary operator statements are easier to read than if/else statements
  • As a longstanding feature of JavaScript, it has excellent cross-browser compatibility

Yet there are situations where programmers should avoid using the ternary operator.

Limitations of the Ternary Operator in JavaScript

  • Conditional statements with longer expressions can be hard to read with the ternary operator’s inline syntax. These expressions could otherwise be split across many lines in an if/else statement, resulting in better readability.
  • Nested conditions are also better expressed as if/else statements than with the ternary operator. Although you can nest conditional statements with the ternary operator, the result is often messy and hard to debug. If/else statements lend themselves better to nested conditions because they are split over many lines. This visual separation makes each condition easier to understand and maintain.

More in JavaScript 8 Common JavaScript Data Structures

Start Using the Ternary Operator in JavaScript

In summary, the ternary operator is a great way of phrasing conditional statements. Although it isn’t suited to dense expressions or nested conditions, it can still replace long if/else statements with shorter, more readable code. Though not to be overused, it is still essential knowledge for any accomplished JavaScript programmer.

Built In’s expert contributor network publishes thoughtful, solutions-oriented stories written by innovative tech professionals. It is the tech industry’s definitive destination for sharing compelling, first-person accounts of problem-solving on the road to innovation.

Great Companies Need Great People. That's Where We Come In.

Using the Ternary Operator in JavaScript

Published on Oct 14, 2022

ternary operator in javascript

The ternary operator can be used as an alternative to an if...else statement. Its minimal syntax can, in some cases, make your code easier to read, and its inline structure makes it particularly useful for conditional assignment.

Ternary operator syntax

The ternary operator has three operands. The first is a condition which is followed by a question mark. The next two operands are expressions separated by a colon. If the condition is truthy, then the first expression is executed, or if the condition is falsy, then the second expression is executed.

The equivalent as an if...else statement would be:

Conditional assignment

The ternary operator is particularly useful for conditional assignment. This is because you can initialize and assign a variable in a single statement. For example:

If this assignment were made using an if...else statement, then you would need two assignment statements and so would not be able to use a const variable type.

This is a case where the ternary operator has an advantage over the if...else statement. The conditional assignment is more concise and arguably more readable. It also enables the use of immutable variables, which can make your code more resilient.

Null checks

In scenarios where you're dealing with variables that might not have a defined value, it can be necessary to check that they have a defined value before using them. This is where you would use a null check. It's particularly important when you need to access properties of a variable, as attempting to access a property of a variable that is null or undefined will result in an error being thrown. Ternary operators are well suited to this task and can be implemented in a single line.

If you tried to access a property on a variable that hadn't been defined, you would encounter the following error: TypeError: Cannot read properties of undefined .

Nested conditions

Ternary operators can be nested to check multiple conditions, similar to an if...else if...else statement. Here is an example of a nested ternary that implements the logic of a game of FizzBuzz.

The same example using an if...else if...else statement would look like this:

The first condition checks if i % 15 is equal to zero. If it's true then FizzBuzz is logged to the console. If it's false , then the second condition is checked. This keeps on going until either all conditions are found to be false , which will result in the value of i being logged to the console, or until one of the conditions is found to be true .

As you can see, the ternary operator is a very versatile and handy operator that enables you to write code that's concise and readable. It has many uses in JavaScript and can assist you with creating applications that are resilient and robust. So next time you're writing JS code, consider how your code might benefit from using a ternary.

Join the RunJS mailing list

You'll receive an occasional newsletter with development updates and articles from the blog. Unsubscribe at any time.

Recent posts

  • 17 Equations that Changed the World - Rewritten in JavaScript
  • 6 Best Code Editors for JavaScript (2023): A Comprehensive Guide
  • How to use the ChatGPT JavaScript API - 3 Easy Steps (2023)
  • 10 Chrome DevTools Tips and Tricks
  • How Hoisting in JavaScript Works
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • JavaScript Tutorial

JavaScript Basics

  • Introduction to JavaScript
  • JavaScript Versions
  • How to Add JavaScript in HTML Document?
  • JavaScript Statements
  • JavaScript Syntax
  • JavaScript Output
  • JavaScript Comments

JS Variables & Datatypes

  • Variables and Datatypes in JavaScript
  • Global and Local variables in JavaScript
  • JavaScript Let
  • JavaScript Const
  • JavaScript var

JS Operators

  • JavaScript Operators
  • Operator precedence in JavaScript
  • JavaScript Arithmetic Operators
  • JavaScript Assignment Operators
  • JavaScript Comparison Operators
  • JavaScript Logical Operators
  • JavaScript Bitwise Operators

JavaScript Ternary Operator

  • JavaScript Comma Operator
  • JavaScript Unary Operators
  • JavaScript Relational operators
  • JavaScript String Operators
  • JavaScript Loops
  • 7 Loops of JavaScript
  • JavaScript For Loop
  • JavaScript While Loop
  • JavaScript for-in Loop
  • JavaScript for...of Loop
  • JavaScript do...while Loop

JS Perfomance & Debugging

  • JavaScript | Performance
  • Debugging in JavaScript
  • JavaScript Errors Throw and Try to Catch
  • Objects in Javascript
  • Introduction to Object Oriented Programming in JavaScript
  • JavaScript Objects
  • Creating objects in JavaScript (4 Different Ways)
  • JavaScript JSON Objects
  • JavaScript Object Reference

JS Function

  • Functions in JavaScript
  • How to write a function in JavaScript ?
  • JavaScript Function Call
  • Different ways of writing functions in JavaScript
  • Difference between Methods and Functions in JavaScript
  • Explain the Different Function States in JavaScript
  • JavaScript Function Complete Reference
  • JavaScript Arrays
  • JavaScript Array Methods
  • Best-Known JavaScript Array Methods
  • What are the Important Array Methods of JavaScript ?
  • JavaScript Array Reference
  • JavaScript Strings
  • JavaScript String Methods
  • JavaScript String Reference
  • JavaScript Numbers
  • How numbers are stored in JavaScript ?
  • How to create a Number object using JavaScript ?
  • JavaScript Number Reference
  • JavaScript Math Object
  • What is the use of Math object in JavaScript ?
  • JavaScript Math Reference
  • JavaScript Map
  • What is JavaScript Map and how to use it ?
  • JavaScript Map Reference
  • Sets in JavaScript
  • How are elements ordered in a Set in JavaScript ?
  • How to iterate over Set elements in JavaScript ?
  • How to sort a set in JavaScript ?
  • JavaScript Set Reference
  • JavaScript Date
  • JavaScript Promise
  • JavaScript BigInt
  • JavaScript Boolean
  • JavaScript Proxy/Handler
  • JavaScript WeakMap
  • JavaScript WeakSet
  • JavaScript Function Generator
  • JavaScript JSON
  • Arrow functions in JavaScript
  • JavaScript this Keyword
  • Strict mode in JavaScript
  • Introduction to ES6
  • JavaScript Hoisting
  • Async and Await in JavaScript

JavaScript Exercises

  • JavaScript Exercises, Practice Questions and Solutions

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.

  • condition: Expression to be evaluated which returns a boolean value.
  • value if true: Value to be executed if the condition results in a true state.
  • value if false: Value to be executed if the condition results in a false state.

Characteristics of Ternary Operator

  • The expression consists of three operands: the condition, value if true, and value if false.
  • The evaluation of the condition should result in either a true/false or a boolean value.
  • The true value lies between “ ? ” & “ : ” and is executed if the condition returns true. Similarly, the false value lies after “:” and is executed if the condition returns false.

Example 1: Below is an example of the Ternary Operator.

Example 2: Below is an example of the Ternary Operator.

Example 3: Below is an example of nested ternary operators. 

Please Login to comment...

Similar reads.

  • javascript-operators
  • Web Technologies

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Ternary Operator Javascript (Write Cleaner Code)

    js ternary without assignment

  2. JavaScript Ternary Operator

    js ternary without assignment

  3. Ternary Operator

    js ternary without assignment

  4. #24 The Ternary (Conditional) Operator

    js ternary without assignment

  5. Ternary Operator JavaScript

    js ternary without assignment

  6. Ternary Operator JavaScript If Statement Tutorial

    js ternary without assignment

VIDEO

  1. online jobs /hand writing Assignment without investment 💯/real app /website

  2. Ternary Operator in Java (?:) || Conditional Operator with Source Code #java #ternary

  3. What are assignment operators in javascript

  4. সি: Operators in C Programming in One Video

  5. Accessing Nested Arrays (Basic JavaScript) freeCodeCamp tutorial

  6. assignment operator in js

COMMENTS

  1. optimization

    361. First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value. This means several things: use ternary expressions only when you have a variable on ...

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

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

  4. javascript

    Here is an example where a non-assignment use comes in handy, specifically to call one of two functions. In a Javascript Promise, which operates on two function arguments, resolve and reject, it is possible to do the following one-liner without violating the intuition of the ternary operator returning a value:

  5. Quick Tip: How to Use 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 ...

  6. How to Use the Ternary Operator in JavaScript

    In this example, I used the ternary operator to determine whether a user's age is greater than or equal to 18. Firstly, I used the prompt() built-in JavaScript function. This function opens a dialog box with the message What is your age? and the user can enter a value. I store the user's input in the age variable.

  7. JavaScript Ternary Operator

    Multiple Ternary Operators Can Make Your Code Unreadable. In the previous examples, we've seen how we can improve our code while maintaining readability. But you have to be careful when using multiple ternary operators. Imagine we had an extra ternary operator in our previous example: const score = 45 const scoreRating = score > 70 ?

  8. Make Your Code Cleaner with JavaScript Ternary Operator

    console .log(message); Code language: JavaScript (javascript) Here's the syntax of the ternary operator: In this syntax, the condition is an expression that evaluates to a Boolean value, either true or false. If the condition is true, the first expression ( expresionIfTrue) executes. If it is false, the second expression ( expressionIfFalse ...

  9. How to Use the JavaScript Ternary Operator

    The Ternary Operator in JavaScript is a conditional control structure that checks for the return value of an expression and executes a block of code based on whether the value is truthy or falsy. It then returns the return value of the executed block. The JavaScript Ternary Operator is also referred to as the Conditional Operator.

  10. Conditional (ternary) operator

    Syntax. Description. Specifications. Browser compatibility. See also. The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement. JavaScript Demo: Expressions - Conditional operator.

  11. JavaScript Ternary Operator (with Examples)

    A ternary operator can be used to replace an if..else statement in certain situations. Before you learn about ternary operators, be sure to check the JavaScript if...else tutorial. What is a Ternary operator? A ternary operator evaluates a condition and executes a block of code based on the condition. Its syntax is: condition ? expression1 ...

  12. Assign only if condition is true in ternary operator in JavaScript

    The reader must know about and understand the meaning of the comma operator and the meaning of the assignment operator when it is used in an expression. More, they have to juggle with the possible values of exp.id == "xyz" struggling to understand when a value is assigned to selectedData and when the callback of Array.some() returns true and why.

  13. JavaScript Ternary Operator

    The Ternary Operator can be used instead of if...else statements to streamline conditional logic in JavaScript. It excels in scenarios where a simple condition needs to determine one of two values or actions. The ternary operator's compact form allows for inline conditional evaluations and assignments, reducing the complexity and length of code ...

  14. Ternary Operator: Better Alternatives

    The ternary operator is a nice way to write concise value assignments without having to write a more lengthy if/else. However it's easy to misuse the ternary operator for things where simpler operators could often have been a better choice. So here are some alternatives for common mistakes.

  15. Ternary Operator in JavaScript Explained

    Strengths of the Ternary Operator in JavaScript. It can represent conditional statements more concisely than if/else statements. In cases where conditions and return values are simple, ternary operator statements are easier to read than if/else statements. As a longstanding feature of JavaScript, it has excellent cross-browser compatibility.

  16. Using the Ternary Operator in JavaScript

    Using the Ternary Operator in JavaScript. Published on Oct 14, 2022. The ternary operator can be used as an alternative to an if...else statement. Its minimal syntax can, in some cases, make your code easier to read, and its inline structure makes it particularly useful for conditional assignment.

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

  18. Java Ternary without Assignment

    Is there a way to do a java ternary operation without doing an assignment or way to fake the assignment? OK, so when you write a statement like this: (bool1 && bool2) ? voidFunc1() : voidFunc2(); there are two distinct problems with the code: The 2nd and 3rd operands of a conditional expression 1 cannot be calls to void methods. Reference: JLS ...

  19. Ternary operator w/o assignement? : r/javascript

    I think the linter is a good source for guidance. If the linter doesn't like it by default, you probably shouldn't do it. For me personally, use specifically of the ternary operator without assignment bugs me. I always want that format to be result = condition ? if-true-value : if-false-value.The use of the short circuiting in logical operators (&& and ||) is a little more ambiguous, though ...

  20. java

    Why can't Ternary operator be used without assignment (variable on the left)? Ask Question Asked 5 years, 4 months ago. Modified 2 years ago. ... this code fails to compile with The left-hand side of an assignment must be a variable. Even though both of above conditions are met(to best of my knowledge). why the code doesn't compile and why it ...

  21. javascript

    1. No, the ternary operator is strictly defined as: With p an expression that results in a boolean (thus a test), vt the value in case p is true and vf in case the test is false. There are no means to introduce a side-effect. The test of course (that can be a function call or anything), can result in side effects.