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

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.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

JavaScript Tutorial

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.
  • Skip to main content
  • Select language
  • Skip to search
  • Conditional (ternary) Operator

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.

Description

If condition is true , the operator returns the value of expr1 ; otherwise, it returns the value of expr2 . For example, to display a different message based on the value of the isMember variable, you could use this statement:

You can also assign variables depending on a ternary result:

Multiple ternary evaluations are also possible (note: the conditional operator is right associative):

You can also use multiple conditions like in a multiple-conditions IF statement

Note: The parentheses are not required, and do not affect the functionality. They are there to help visualize how the outcome is processed.

You can also use ternary evaluations in free space in order to do different operations:

You can also do more than one single operation per case, separating them with a comma:

You can also do more than one operation during the assignation of a value. In this case, the last comma-separated value of the parenthesis will be the value to be assigned .

Specifications

Specification Status Comment
Draft  
Standard  
Standard  
Standard Initial definition. Implemented in JavaScript 1.0.

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
  • if statement

Document Tags and Contributors

  • 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
  • Iterators and generators
  • Meta programming
  • 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.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • 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
  • 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 each...in
  • function declaration
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • 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: 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: More arguments needed
  • TypeError: can't access dead 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: cyclic object value
  • TypeError: invalid 'in' 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
  • 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
  • ECMAScript Next 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
  • 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 Ternary Operator

The Ternary Operator in JavaScript is a shortcut for writing simple if-else statements. It’s also known as the Conditional Operator because it works based on a condition. The ternary operator allows you to quickly decide between two values depending on whether a condition is true or false.

How Does the Ternary Operator Work?

The ternary operator works with three parts:

  • Condition: A statement that returns true or false.
  • Value if True: What happens if the condition is true?
  • Value if False: What happens if the condition is false?
Expression to be evaluated which returns a boolean value
Value to be executed if the condition results in a true state
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. 

JavaScript Ternary Operator – FAQs

What is the ternary operator in javascript.

The ternary operator is a shorthand for the if-else statement. It takes three operands and is the only operator that takes three operands. It is used to evaluate a condition and return one of two values based on whether the condition is true or false.

What is the syntax of the ternary operator?

The syntax of the ternary operator is: condition ? expressionIfTrue : expressionIfFalse.

How does the ternary operator work?

The ternary operator evaluates the condition. If the condition is true, it returns expressionIfTrue; otherwise, it returns expressionIfFalse.

Can you use the ternary operator for multiple conditions?

Yes, you can nest ternary operators to handle multiple conditions. However, this can make the code hard to read, so it’s usually better to use if-else statements for complex conditions.

Is the ternary operator only used for returning values?

Primarily, the ternary operator is used for returning values based on a condition. However, it can also be used to execute code conditionally, but this is not recommended as it can make the code less readable.

Please Login to comment...

Similar reads.

  • Web Technologies
  • javascript-operators
  • Best PS5 SSDs in 2024: Top Picks for Expanding Your Storage
  • Best Nintendo Switch Controllers in 2024
  • Xbox Game Pass Ultimate: Features, Benefits, and Pricing in 2024
  • Xbox Game Pass vs. Xbox Game Pass Ultimate: Which is Right for You?
  • Full Stack Developer Roadmap [2024 Updated]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

How to Use the Ternary Operator in JavaScript

The ternary operator is a concise way of expressing conditional statements in a single line of JavaScript code. Our expert explains how it works.

Rory Spanton

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.

Recent Javascript Articles

Compiler vs. Interpreter in Programming

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

The JavaScript Ternary Operator as a Shortcut for If/Else Statements

Stone/Cavan Images/Getty Images

  • Javascript Programming
  • PHP Programming
  • Java Programming
  • Delphi Programming
  • C & C++ Programming
  • Ruby Programming
  • Visual Basic
  • B.S., Computer Science, North Carolina State University

The conditional ternary operator in JavaScript assigns a value to a variable based on some condition and is the only JavaScript operator that takes three operands.

The ternary operator is a substitute for an if statement in which both the if and else clauses assign different values to the same field, like so:

The ternary operator shortens this if/else statement into a single statement:

If condition is true, the ternary operator returns the value of the first expression; otherwise, it returns the value of the second expression. Let's consider its parts: 

  • First, create the variable to which you want to assign a value, in this case, result . The variable result will have a different value depending on the condition.
  • Note that on the right-hand side (i.e. the operator itself), the condition is first.
  • The condition is always followed by a question mark ( ? ), which can basically be read as "was that true?"
  • The two possible results come last, separated by a colon ( : ).

This use of the ternary operator is available only when the original if statement follows the format shown above — but this is quite a common scenario, and using the ternary operator can be far more efficient.

Ternary Operator Example

Let's look at a real example.

Perhaps you need to determine which children are the right age to attend kindergarten. You might have a conditional statement like this:

Using the ternary operator, you could shorten the expression to:

This example would, of course, return "Old enough."

Multiple Evaluations

You can include multiple evaluations, as well:

Multiple Operations

The ternary operator also allows the inclusion of multiple operations for each expression, separated by a comma:

Ternary Operator Implications

Ternary operators avoid otherwise verbose code , so on the one hand, they appear desirable. On the other hand, they can compromise readability — obviously, "IF ELSE" is more easily understood than a cryptic "?".

When using a ternary operator —  or any abbreviation  — consider who will be reading your code. If less-experienced developers may need to understand your program logic, perhaps the use of the ternary operator should be avoided. This is especially true if your condition and evaluations are complex enough that you would need to nest or chain your ternary operator. In fact, these kinds of nested operators can impact not only readability but debugging.

As with any programming decision, be sure to consider context and usability before using a ternary operator. 

  • An Abbreviated JavaScript If Statement
  • JavaScript Nested IF/ELSE Statements
  • The Dollar Sign ($) and Underscore (_) in JavaScript
  • How to Return a Value in JavaScript
  • How to Create a Continuous Text Marquee in JavaScript
  • How to Create a Continuous Image Marquee With JavaScript
  • Moving JavaScript Out of the Web Page
  • How to Create and Use External JavaScript Files
  • How to Convert Numbers Into Words Using JavaScript
  • JavaScript and Emails
  • Add the Concentration Memory Game to Your Web Page
  • Why JavaScript
  • Introduction to JavaScript
  • Free JavaScript Download
  • Is JavaScript Hard to Learn?
  • JavaScript and JScript : What's the Difference?

TutorialsTonight Logo

Ternary Operator Javascript - Write Cleaner Code

In this tutorial, you will know about the ternary operator in JavaScript , how to use it and how to write cleaner code using it 👨‍💻.

Ternary Operator in JavaScript

The ternary operator is a shorthand for an if-else statement . It is a concise way to check a condition and return a value based on it.

The ternary operator is the only javascript operator which takes 3 operands for the operations .

The basic syntax of the ternary operator is as follows:

Ternary operator in Javascript

Here is the most basic example of a ternary operator. Where we are just using it to print a message.

Let's see another example that checks if a person is older than 18 years or not and returns a message accordingly.

Another example, let's say we have a variable score and we want to check if the student passed or failed.

Ternary operator VS if-else

The following table shows the differences between the ternary operator and the if-else statement.

Ternary Operatorif-else Statement
Syntax: Syntax:
Short and concise way to write a simple statementMore versatile, can be used for more complex conditions
Best for simple conditions and when you only need to return one valueCan be used for multiple conditions and can execute different code based on the outcome
Limited to only one conditionCan handle multiple conditions
Limited to only one value returnCan handle multiple return values

The following example compares the ternary operator and if-else statement.

  • Ternary operator

You can see that the ternary operator is much easier to read and understand than if-else.

Ternary operator without else

The name of the ternary operator itself claims that it takes 3 operands. In the ideal case, you need to provide all 3 operands to make it work.

But you can also work without the else part using different syntax.

Let's see an example of a ternary operator without else.

Ternary operator multiple conditions

The ternary operator can also be used to check multiple conditions and assign a value to a variable based on that.

Let's see an example of how to take multiple conditions with a ternary operator.

Here is another example of multiple conditions with the ternary operator.

If you do not understand how it resulted in "adult" then here is a little more explanation.

The ternary operator is a combination of multiple conditions. The condition given ( age < 18 ) is false in the above code so it jumped to the next condition ( age < 65 ) and return true .

Look at the code below it is the ternary operator in multiple lines .

Same as the above code

Nested Ternary Operator javascript

Ternary operators can also be nested to check multiple conditions same as if-else but it becomes more complicated to read and also is not recommended.

First, look at the code to find leap year using if-else statements .

Now let's see how to use the ternary operator to check if a year is a leap year.

Ternary operator in loops

Ternary operators can also be used in loops. It is very useful when you want to check a condition in a loop.

Let's see an example of how to use the ternary operator in a loop.

Ternary operator Examples

Here are 10 different examples that use the ternary operator.

1. Checking for odd or even numbers:

2. assigning a value to a variable based on a condition:, 3. returning different values based on a condition:, 4. setting a default value for a variable:, 5. checking if a string is empty or not:, 6. choosing between two different actions based on a condition:, 7. setting a variable to a string or number based on a condition:, 8. displaying a message based on a condition:, 9. assign a variable to the maximum of two values:, 10. check if a number is between two numbers:, frequently ask questions.

How do you use multiple conditions in a ternary operator?

You can separate multiple conditions with logical operators like && or || and use the ternary operator as it is.

Can ternary operator have multiple statements?

Yes, you can have multiple statements inside the ternary operator. For example: a ? b : c ? d : e .

Can ternary operator have multiple lines?

Yes, you can have multiple lines inside the ternary operator. For example:

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript operators.

Javascript operators are used to perform different types of mathematical and logical computations.

The Assignment Operator = assigns values

The Addition Operator + adds values

The Multiplication Operator * multiplies values

The Comparison Operator > compares values

JavaScript Assignment

The Assignment Operator ( = ) assigns a value to a variable:

Assignment Examples

Javascript addition.

The Addition Operator ( + ) adds numbers:

JavaScript Multiplication

The Multiplication Operator ( * ) multiplies numbers:

Multiplying

Types of javascript operators.

There are different types of JavaScript operators:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • String Operators
  • Logical Operators
  • Bitwise Operators
  • Ternary Operators
  • Type Operators

JavaScript Arithmetic Operators

Arithmetic Operators are used to perform arithmetic on numbers:

Arithmetic Operators Example

Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation ( )
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement

Arithmetic operators are fully described in the JS Arithmetic chapter.

Advertisement

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

The Addition Assignment Operator ( += ) adds a value to a variable.

Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y

Assignment operators are fully described in the JS Assignment chapter.

JavaScript Comparison Operators

Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator

Comparison operators are fully described in the JS Comparisons chapter.

JavaScript String Comparison

All the comparison operators above can also be used on strings:

Note that strings are compared alphabetically:

JavaScript String Addition

The + can also be used to add (concatenate) strings:

The += assignment operator can also be used to add (concatenate) strings:

The result of text1 will be:

When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers

Adding two numbers, will return the sum, but adding a number and a string will return a string:

The result of x , y , and z will be:

If you add a number and a string, the result will be a string!

JavaScript Logical Operators

Operator Description
&& logical and
|| logical or
! logical not

Logical operators are fully described in the JS Comparisons chapter.

JavaScript Type Operators

Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type

Type operators are fully described in the JS Type Conversion chapter.

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

Operator Description Example Same as Result Decimal
& AND 5 & 1 0101 & 0001 0001  1
| OR 5 | 1 0101 | 0001 0101  5
~ NOT ~ 5  ~0101 1010  10
^ XOR 5 ^ 1 0101 ^ 0001 0100  4
<< left shift 5 << 1 0101 << 1 1010  10
>> right shift 5 >> 1 0101 >> 1 0010   2
>>> unsigned right shift 5 >>> 1 0101 >>> 1 0010   2

The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers. Because of this, in JavaScript, ~ 5 will not return 10. It will return -6. ~00000000000000000000000000000101 will return 11111111111111111111111111111010

Bitwise operators are fully described in the JS Bitwise chapter.

Test Yourself With Exercises

Multiply 10 with 5 , and alert the result.

Start the Exercise

Test Yourself with Exercises!

Exercise 1 »   Exercise 2 »   Exercise 3 »   Exercise 4 »   Exercise 5 »

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

logo

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

' data-src=

Operators are essential elements of JavaScript code. They allow developers to perform operations on operands or values in code. Based on the number of operands needed, JavaScript operators can be categorized as unary, binary or ternary. Understanding the differences between these operator types can help write cleaner, more efficient code. This comprehensive 2600+ word guide will explain unary, binary and ternary operators through definitions, examples and use cases.

Introduction to Operands, Operators and Operations

Before diving into operator categories, let’s define some key terms:

Operand : The value that an operator acts on. For example, in the operation 10 + 20 , 10 and 20 are operands.

Operator : The symbol that performs an operation. For the expression 10 + 20 , + is the operator.

Operation : The process that combines operands with an operator to produce a result. 10 + 20 is an arithmetic operation using the + operator.

Operators can be categorized by the number of operands they work on:

  • Unary : Requires one operand
  • Binary : Requires two operands
  • Ternary : Requires three operands

Now let’s explore some common examples of each operator type in JavaScript.

Section 1: Unary Operators

Unary operators require only one operand for the operation. Some examples include:

Returns the type of the operand as a string:

The typeof operator can check the type of any JavaScript value like strings, numbers, arrays, objects, functions and more. It‘s useful for:

  • Type checking before further processing
  • Validation functions
  • Debugging unexpected values

Using typeof prevents errors trying to access properties of an unexpected data type. Overall it provides a simple way to inspect values programmatically.

Deletes a property from an object or an element from an array:

The delete operator is an easy way to remove object properties and clear array elements. However, it leaves undefined holes in arrays rather than reindexing the elements.

Logical NOT (!)

Inverts a boolean value:

The logical NOT operator flips true to false and vice versa. This is helpful for inverting logical conditions and coercing truthy/falsy values:

The ! operator is commonly used in computer science for bitwise operations and to represent mathematical set negation.

Unary Negation (-)

Negates a number:

Unary negation flips the sign of a number, making it negative or positive. This serves basic arithmetic operations. It also has a popular use case for descending sort functions:

Here unary - cleverly inverts the subtraction direction to reverse standard ascending sort order.

Increment (++)

Increments a number by 1:

Similarly, the decrement operator -- decreases a value by 1. Incrementing and decrementing by 1 allows easy count tracking and numeric progression:

These operators work similarly to += 1 and -= 1 but provide cleaner syntax. Prefix vs. postfix incrementing/decrementing behavior is an important distinction as well.

Additional Unary Operators

Some additional unary operators include:

  • void : Evaluates an expression without returning a value
  • new : Constructs an instance of an object
  • yield : Pauses and returns a value in a generator
  • await : Suspends asynchronous execution pending promise resolution
  • super() : Calls parent class constructor

These operators have specific use cases that enable JavaScript language capabilities like asynchronous programming, object-oriented code, and more. Memorizing every unary operator isn’t critical – just remember that all operators with a single operand after them fall into this category.

Overall, unary operators provide concise syntax for common operations involving a single operand. Next let‘s explore the popular binary operators.

Section 2: Binary Operators

Binary operators require two operands, one on each side of the operator, to perform an operation. Some examples include:

Arithmetic Operators

Perform math operations:

These basic math operators support all numeric calculations in JavaScript. Understanding PEMDAS rules is important – as P arentheses, E xponents, M ultiplication, D ivision, A ddition, S ubtraction occurs in that order.

For example:

Also crucial is the difference between math + and string concatenation with + :

JavaScript coerces numbers to strings for concatenation. Explicitly convert with String() to prevent unexpected behavior.

Assignment Operators

Assign values:

Assignment operators modify the value of a variable with the evaluation result. This shorthand notation speeds writing code.

The standard assignment = assigns the value on the right to the variable on left. Augmented assignments like += provide shorthand for x = x operator y.

Comparison Operators

Compare operand values:

Comparison operators test conditions and return boolean true/false if the condition passes. These statements power control flow code like if/else statements and loops.

Understanding the difference between loose equality == and strict === is important. Strict equality requires both value and type match:

Here loose == coercion matches the string to integer 5. But strict === compares both value AND type, so it correctly returns false since a string is not strictly equal to a number.

Logical Operators

Boolean logic:

Logical operators combine boolean operand values to return a single boolean. AND returns true only if both operands are true, while OR returns true if either operand is true.

These operators become very powerful alongside comparison expressions:

Here the AND and OR conditions add boolean logic flexibility.

Bitwise Operators

Low-level bit manipulation:

Bitwise operators treat operand values as binary representations rather than numbers. The operators perform bit logic at the individual bit level:

This works because:

  • Bitwise AND & turns bits off
  • Bitwise OR | turns bits on

Though rarely used, these operators enable low-level manipulation useful for tasks like encryption, compression, graphics and more.

Additional Binary Operators

Some additional JavaScript binary operators include:

  • Exponentiation/power **
  • Left/right bit shift << and >>
  • Bitwise XOR, NOT
  • In operator
  • Instanceof operator

These operators have specific use cases but are less common than the core set of arithmetic, assignment, comparison operators highlighted above.

Overall, binary operators mix two operand values to produce new values. Mastering binary arithmetic, assignment, comparison and logical operators in particular establishes core programming foundations in any language.

Section 3: Ternary Operator

The ternary operator is the only JavaScript operator that takes three operands. It has the following syntax:

If the condition evaluates to true, the first expression executes. Otherwise, the second expression executes instead.

Here is an example usage:

This checks if age is over 18, and conditionally assigns either true or false to the accessAllowed variable based on the condition.

The ternary operator provides a shortcut for basic if/else conditional logic:

As you can see, the ternary approach condenses multiple lines of code down to a single-line conditional expression.

Some advantages of using ternary operators include:

  • More concise syntax improving readability
  • Prevent nested if/else pyramid code
  • Enable interesting logic flows and patterns

However overusing the ternary operator can have downsides:

  • Excessively long single-line statements
  • Unnecessary premature optimization
  • Complicated conditional logic

In general save the ternary operator for simple true/false conditionals and avoid ternary pyramids!

Here are some more examples of using ternaries:

Function Shorthand

Object Assignment

This concise ternary syntax shines for handling simple dynamic situations.

Section 4: Operator Precedence

When multiple operators appear together in an expression, operator precedence governs which operations run first.

Operator precedence ranks operators based on which bindings are stronger. For example, exponentiation has a higher precedence than multiplication or division, which has precedence over addition and subtraction.

Here is an operator precedence hierarchy table:

CategoryOperators
Exponentiation
Multiplicative
Additive
Comparison
Equality
Logical AND
Logical OR
Assignment

Higher precedence towards the top, lower towards bottom.

When operators of different precedence appear together:

Here multiplication * happens before addition + due to higher precedence. But parentheses () override to explicitly do addition first.

Understanding operator precedence helps properly chain mathematical and logical operators without unintended behavior. Consult an operator precedence table or add parentheses when in doubt!

Bonus Advanced Topics

Here are some more advanced ways operators are used in JavaScript:

Short-Circuit Evaluation

Logical operators use short-circuit evaluation – meaning they stop evaluation as soon as a definite result is determined.

Example WITH short-circuiting:

This avoids needless computation for optimization.

Strict Equality Guide

Strict equality === is recommended over loose equality == for comparing values:

  • Avoids unexpected type coercion
  • Prevents hard to spot bugs
  • Requires explicit checking of types
  • More code than loose checks

Get in the habit of using === over == especially for crucial logic!

Unary and Binary Operators Together

You can even combine unary and binary operators for more complex expressions:

Here unary (negation, not, increment) and binary operators (+ addition) are used together. This demonstrates the flexibility in chaining JavaScript operators.

Creative Arithmetic Uses

Beyond basic math, developers leverage arithmetic and modulus operators creatively:

  • Randomization functions
  • Cyclic iteration
  • Interval spacing algorithms

By cleverly applying numeric operators, mathematical patterns emerge to solve programming challenges.

Performance Optimizations

Specialized operators like increment ++ and decrement — have optimized performance over standard += and -= assignment. The CPU translates ++/– to efficient single assemble instruction.

Likewise bitwise operations directly access hardware level instructions. Modern JavaScript engines optimize performance for arithmetic as well including strength reduction and inline caching methodologies.

Operator Associativity

Most JavaScript operators are left-to-right associative meaning they group left to right:

But some like assignment = are right associative:

Associativity defines how operations are structured, like parentheses forcing certain groupings.

This covers some next level operator capabilities!

I hope this 2600+ word guide gave you a solid and comprehensive understanding of the categories of JavaScript operators including unary, binary and single ternary forms. Properly wielding operators from arithmetic and assignment to comparisons and logical flows builds a crucial foundation in JavaScript. Please reach out with any questions!

' data-src=

Dr. Alex Mitchell is a dedicated coding instructor with a deep passion for teaching and a wealth of experience in computer science education. As a university professor, Dr. Mitchell has played a pivotal role in shaping the coding skills of countless students, helping them navigate the intricate world of programming languages and software development.

Beyond the classroom, Dr. Mitchell is an active contributor to the freeCodeCamp community, where he regularly shares his expertise through tutorials, code examples, and practical insights. His teaching repertoire includes a wide range of languages and frameworks, such as Python, JavaScript, Next.js, and React, which he presents in an accessible and engaging manner.

Dr. Mitchell’s approach to teaching blends academic rigor with real-world applications, ensuring that his students not only understand the theory but also how to apply it effectively. His commitment to education and his ability to simplify complex topics have made him a respected figure in both the university and online learning communities.

Similar Posts

How to Create a High-Performance Binary Tree Viewer in C

How to Create a High-Performance Binary Tree Viewer in C

As full-stack developers, we don‘t always have the luxury of debugging complex data structures by printing…

What I Learned from Creating a Video Game as a Coding Beginner

What I Learned from Creating a Video Game as a Coding Beginner

As someone who loves playing video games, I‘ve always been fascinated by the coding and technology…

This is the only résumé objective advice you need to get hired

This is the only résumé objective advice you need to get hired

How Developers Can Optimize Objectives to Stand Out Crafting a resume that stands out is no…

How to Build a Todo List with React Hooks

How to Build a Todo List with React Hooks

React Hooks are an exciting new feature that was added in React 16.8. They allow you…

Implement Event-Driven Architecture with React and FastAPI

Implement Event-Driven Architecture with React and FastAPI

Event-driven architecture is a popular pattern for building modern, scalable applications. The core idea is that…

Graph Algorithms and Data Structures Explained with Java and C++ Examples

Graph Algorithms and Data Structures Explained with Java and C++ Examples

Graphs are fundamental data structures that model connections and relationships. There are many real-world examples that…

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

freeCodeCamp

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

Learn to code. Build projects. Earn certifications—All for free.

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

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Javascript object declaration with ternary operator

I'm declaring an object inside one of my components like below:

But now I wanted to do this declaration dynamically depends on a specific value, like below:

Is this possible. I know I can do it with nested ternary operator. But inside the object structure any simple line that can do that trick?

Update: object values can be easily set using ternary inside the object declaration, but this is for object key so this is not a duplicate of this . Also, in the above example I have put a simple object. Image if the objects have some child and ternary conditions within.

  • conditional-operator

Balaji's user avatar

  • Does this answer your question? Is it possible to add dynamically named properties to JavaScript object? –  Heretic Monkey Commented Oct 20, 2021 at 15:44

4 Answers 4

I'd avoid a ternary operator altogether because they're confusing to read in a lot of situations. Instead I would create a dictionary that maps user types to string values, and then create the property dynamically with that information.

const userType = 'teacher'; const dict = { teacher: 'tdepartment', student: 'sdepartment' }; const data = { user: 'id', userRole: 'role', [`${userType}Department`]: dict[userType] } console.log(data);

Andy's user avatar

I think this could be refactored into

let usertype = 'teacher'; let departmentProperty = usertype === 'teacher' ? 'teacherdepartment' : 'studentDepartment'; let departmentValue = usertype === 'teacher' ? 'teacherdepartmentValue' : 'studentDepartment'; const data = { user: 'id', userRole: 'role', [departmentProperty]: departmentValue, }; console.log(data)

jellytran's user avatar

Try with conditional operator for both key and value. Keys can be made dynamic by adding [] around the key expression.

Pseude Code

Working Code

const usertype = 'student'; const tdepartment = 'tdepartment'; const sdepartment = 'sdepartment'; const id = 'id'; const role = 'role'; const data = { user: id, userRole: role, [usertype=='teacher'? 'teacherdepartment' : 'studentDepartment']: usertype=='teacher'? tdepartment: sdepartment, }; console.log(data)

Nitheesh's user avatar

While this can be done in a "one-liner" IMO to preserve readability it shouldn't be.

Instead, check usertype and create an object to include in the resulting data object. This way the changes based on usertype are isolated and easy to reason about. It also allows for additional changes based on usertype as it's isolated from the static properties.

Dave Newton's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript conditional-operator or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • How can I support a closet rod where there's no shelf?
  • How do you ensure that calendar invites won't be moved out of your inbox when your rules are executed?
  • BASH - Find file with regex - Non-recursively delete number-only filenames in directory
  • "Truth Function" v.s. "Truth-Functional"
  • Engaging students in the beauty of mathematics
  • Is it possible for one wing to stall due to icing while the other wing doesn't ice?
  • Does any row of Pascal's triangle contain a Pythagorean triple?
  • How can I analyze the anatomy of a humanoid species to create sounds for their language?
  • Why was Panama Railroad in poor condition when US decided to build Panama Canal in 1904?
  • How do I go about writing a tragic ending in a story while making it overall satisfying to the reader?
  • Two sisters live alone in a house after the rest of their family died
  • A journal has published an AI-generated article under my name. What to do?
  • "Tail -f" on symlink that points to a file on another drive has interval stops, but not when tailing the original file
  • Electrical panel not sending 240
  • Can a V22 Osprey operate with only one propeller?
  • Use pgf string as property value
  • How can I verify integrity of the document types?
  • Did Queen (or Freddie Mercury) really not like Star Wars?
  • How much technological progress could a group of modern people make in a century?
  • How can I remove this towel rail mount from my wall?
  • How would platypus evolve some sort of digestive acid?
  • Is Produce Flame a spell that the caster casts upon themself?
  • What film is it where the antagonist uses an expandable triple knife?
  • MSSQL - query runs for too long when filtering after a certain date

ternary operator with assignment javascript

IMAGES

  1. Output

    ternary operator with assignment javascript

  2. Ternary Operator in JavaScript: JavaScript Tutorials #13

    ternary operator with assignment javascript

  3. Using the Ternary Operator in JavaScript

    ternary operator with assignment javascript

  4. Learn JavaScript Operators

    ternary operator with assignment javascript

  5. How to Use the Ternary Operator in JavaScript

    ternary operator with assignment javascript

  6. JavaScript Ternary Operator

    ternary operator with assignment javascript

VIDEO

  1. Java Script Logical Operator Lesson # 08

  2. es6 Ternary Operator

  3. ES6 Ternary Operator in depth

  4. What is Ternary Operator in JavaScript..? ⁉️🤯 #javascript #webdevelopment

  5. JavaScript Exercise 3: Operators

  6. Ternary Operator In JavaScript

COMMENTS

  1. Conditional (ternary) operator

    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.

  2. Javascript ternary operator and assignment

    It works perfectly: > var t = 1 == 1 ? 1 : 0; undefined. > t. 1. You could say that the return value of the assignment operation is undefined, not the value of t. Edit: But actually if I read the specification correctly, it seems that it should return the value of the expression. As @T.J. Crowder mentioned, it seems the var is responsible for ...

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

  5. JavaScript Ternary Operator (with Examples)

    A ternary operator evaluates a condition and executes a block of code based on the condition. Its syntax is: condition ? expression1 : expression2. 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 ...

  6. Make Your Code Cleaner with JavaScript Ternary Operator

    Here's the syntax of the ternary operator: condition ? expressionIfTrue : expressionIfFalse; Code language: JavaScript (javascript) 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.

  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. Conditional (ternary) Operator

    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. Syntax condition? expr1: expr2 Parameters condition (or conditions) An expression that evaluates to true or false. expr1, expr2 Expressions with values of any type. Description

  9. JavaScript Ternary Operator

    The Ternary Operator in JavaScript is a shortcut for writing simple if-else statements. It's also known as the Conditional Operator because it works based on a condition. The ternary operator allows you to quickly decide between two values depending on whether a condition is true or false.

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

  11. How to Use the Ternary Operator in JavaScript

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

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

  13. The JavaScript Ternary Operator as a Shortcut for If/Else ...

    The conditional ternary operator in JavaScript assigns a value to a variable based on some condition and is the only JavaScript operator that takes three operands. The ternary operator is a substitute for an if statement in which both the if and else clauses assign different values to the same field, like so:

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

  15. Ternary Operator Javascript

    console.log(group); Run Here. If you do not understand how it resulted in "adult" then here is a little more explanation. The ternary operator is a combination of multiple conditions. The condition given (age < 18) is false in the above code so it jumped to the next condition (age < 65) and return true. Look at the code below it is the ternary ...

  16. JavaScript Operators

    JavaScript Assignment. The Assignment Operator (=) assigns a value to a variable: ... ternary operator: Note. Comparison operators are fully described in the JS Comparisons chapter. JavaScript String Comparison. All the comparison operators above can also be used on strings: Example.

  17. Learn JavaScript Operators

    The second group of operators we're going to explore is the assignment operators. Assignment operators are used to assign a specific value to a variable. The basic assignment operator is marked by the equal = symbol, and you've already seen this operator in action before: let x = 5; After the basic assignment operator, there are 5 more ...

  18. Javascript nested ternary operator

    "I'm trying to re-write existing code into the ternary operator way." — Don't. As you have noticed, it is hard to understand. Don't make more work for whomever has to maintain your code. They'll hate you for it. That person is likely to be you but 6 months older. -

  19. Unary, Binary, And Ternary Operators In JavaScript

    Overall, binary operators mix two operand values to produce new values. Mastering binary arithmetic, assignment, comparison and logical operators in particular establishes core programming foundations in any language. Section 3: Ternary Operator. The ternary operator is the only JavaScript operator that takes three operands. It has the ...

  20. Unary, Binary, and Ternary Operators in JavaScript

    It's about why a ternary operator is not a conditional operator in JavaScript. Wrap Up. 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 ...

  21. Self-assignment through ternary operator

    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.

  22. Javascript object declaration with ternary operator

    Update: object values can be easily set using ternary inside the object declaration, but this is for object key so this is not a duplicate of this. Also, in the above example I have put a simple object. Image if the objects have some child and ternary conditions within. javascript. conditional-operator.