Quick Tip: How to Use the Ternary Operator in JavaScript

Dianne Pena

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:

Using the Ternary Operator for Value Assignment

One of the most common use cases of ternary operators is to decide which value to assign to a variable. Often, a variable’s value might depend on 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:

Using the Ternary Operator for Executing Expressions

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.

Using the Ternary Operator for Null Checks

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.

Nested Conditions

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 .

CodePen Example

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

FAQs on How to Use the Ternary Operator in JavaScript

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!"

  • 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

Browser compatibility.

  • if statement

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.

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 comparison and logical operators.

Comparison and Logical operators are used to test for true or false .

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between variables or values.

Given that x = 5 , the table below explains the comparison operators:

Advertisement

How Can it be Used

Comparison operators can be used in conditional statements to compare values and take action depending on the result:

You will learn more about the use of conditional statements in the next chapter of this tutorial.

Logical Operators

Logical operators are used to determine the logic between variables or values.

Given that x = 6 and y = 3 , the table below explains the logical operators:

Conditional (Ternary) Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

If the variable age is a value below 18, the value of the variable voteable will be "Too young", otherwise the value of voteable will be "Old enough".

Comparing Different Types

Comparing data of different types may give unexpected results.

When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison. An empty string converts to 0. A non-numeric string converts to NaN which is always false .

When comparing two strings, "2" will be greater than "12", because (alphabetically) 1 is less than 2.

To secure a proper result, variables should be converted to the proper type before comparison:

The Nullish Coalescing Operator (??)

The ?? operator returns the first argument if it is not nullish ( null or undefined ).

Otherwise it returns the second argument.

The nullish operator is supported in all browsers since March 2020:

The Optional Chaining Operator (?.)

The ?. operator returns undefined if an object is undefined or null (instead of throwing an error).

The optional chaining operator is supported in all browsers since March 2020:

Test Yourself With Exercises

Choose the correct comparison operator to alert true , when x is greater than y .

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

Operators are constructs which behave generally like functions, but which differ syntactically or semantically from usual functions.

Types of operators

Unary operators, binary operators, the ternary operator (conditional operator).

condition ? x : y

Conditional Operator

condition ? expression : expression

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.

MDN // Conditional Operator

As an expression:

To declare a variable:

To create a property:

Multiple ternary evaluations

Multiple operations, arithmetic operators.

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

MDN // Arithmetic Operators

The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number , if it isn't already.

Note: NaN is a property of the global object. MDN // NaN

The unary negation operator precedes its operand and negates it.
The addition operator produces the sum of numeric operands or string concatenation.

Concatenation

Addition operators are parsed from left to right

Subtraction -

The subtraction operator subtracts the two operands, producing their difference.
The division operator produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.

Note: The global Infinity property is a numeric value representing infinity. MDN | Infinity

Multiplication *

The multiplication operator produces the product of the operands.
The multiplication operator has higher precedence than the addition operator.

Remainder %

Returns the remainder left over when one operand is divided by a second operand.

Exponentiation **

The exponentiation operator returns the result of raising first operand to the power second operand.

Increment ++

x ++ or ++ x

The increment operator increments (adds one to) its operand and returns a value.

Decrement --

x -- or -- x

The decrement operator decrements (subtracts one from) its operand and returns a value.

Assignment operators

The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand.

MDN // Assignment Operators

Simple Assignment

Simple assignment operator which assigns a value to a variable.

Compound assignment

Destructuring assignment.

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.

MDN // Destructuring assignment

Array Destructuring

With arrays, destructuring is made by order

With destructuring:

Without destructuring:

Destructuring declares new variables, and follows the same rules as any variable declaration.

Note: as we are declaring new variables y and z and asigning a value, we need to use var , otherwise variables will be declared on global scope.

Direct assignment

A variable can be assigned its value via destructuring separate from the variable's declaration.

without destructuring:

with destructuring:

Default values

A variable can be assigned a default, in the case that the value pulled from the array is undefined.

Note: Notice that default values only works with undefined values, not with null or falsey values.

Swapping variables

Two variables values can be swapped in one destructuring expression.

Skipping values

You can ignore return values that you're not interested in

Nested array destructuring

Object destructuring.

With objects, destructuring is made by property name, not by order

Renaming properties

Default values or renamed properties, destructuring function parameters, nested object and array destructuring, complex destructuring, comparison operators.

JavaScript has both strict and type–converting comparisons.

MDN // Comparison Operators

Abstract comparison

Converts the operands to the same type before making the comparison.

Abstract equality

Equality of objects.

Two distinct objects are never equal for either strict or abstract comparisons. An expression comparing objects is only true if the operands reference the same object.

Note: The two objects are difference objects, in different allocation. They are not the same object .

Abstract inequality

Type conversion rules, string == number.

The string is converted to a number value.

Boolean == Number

The Boolean operand is converted to 1 if it is true and 0 if it is false.

Object == Number || Object == String

JavaScript attempts to return the default value for the object.

Working with objects

Each of these operators will call the valueOf() function on each operand before a comparison is made. Then, the primitive values are compared

MDN // Object.protrotype.valueOf()

Enforcing valueOf() :

Strict comparison

A strict comparison is only true if the operands are of the same type and the contents match.

Strict equality

Strict inequality, relational operators, logical operators.

expression && expression

expression || expression

! expression

Logical operators are typically used with Boolean (logical) values However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

MDN // Logical Operators

Logical AND

The return is not true or false , it's the last evaluated expression

Expression conversion

With non-Boolean values, "falsey" expressions are evaluated to false: undefined , null , NaN , 0 , ""

Note: The return is not true or false , it's the last evaluated expression.

Logical NOT

Short-circuit evaluation.

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation.

Using it for logic

is the same as:

Other unary operators

An unary operation is an operation with only one operand.
The delete operator deletes an object, an object's property, or an element at a specified index in an array.

MDN // Operators > delete

Objects (and arrays) can be deleted only if they are declared implicitly

The typeof operator returns a string indicating the type of the unevaluated operand.

Spread operator

The spread syntax allows an expression to be expanded in places where comma separated variables are expected.

MDN // Spread operator

numbers passed as a single argument to console.log :

numbers spread, as separated arguments:

which is the same as:

Spreading arrays

Array concat, array insertion, array clone.

arr2 becomes 1,2,3,4 , arr stays the same

Spreading objects

Spread with overriding, can't spread an object into an array, spread arguments, spread operator as rest parameter.

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

Getting all arguments of a func

Arguments vs ...args .

arguments is an iterable (array-like), but not an Array

Array of arguments

arguments built-in variable

Selective rest parameter

... is usefull to get "the rest of the arguments"

Spreading arguments

Rest paramater in array destructure

Read the slides again, and we'll start a small quiz on operators.

01. What would be the output of each code?

01. solution, 02. what would be the output of this code, 02. solution, 03. what would be the output of this code, 03. solution, 04. what would be the output of this code, 04. solution, 05. what would be the output of this code, 05. solution, 06. what would be the output of this code, 06. solution.

String is iterable, so you can spread them.

07. What would be the output of this code?

07. solution, 08. what would be the output of this code, 08. solution.

GoLinuxCloud

How to check if undefined in JavaScript? [SOLVED]

JavaScript is a popular programming language used for building web applications and creating interactive user interfaces. One of the common tasks in JavaScript development is checking if a variable is undefined. An undefined variable is one that has been declared but not assigned a value or has been explicitly assigned the value of "undefined".

There are different ways to check if a variable is undefined in JavaScript, including using the typeof operator, the comparison operator ( === ) with the value undefined, or the use of the ternary operator. Each of these methods has its advantages and disadvantages, and the choice of which one to use depends on the specific scenario and the coding style of the developer.

In this article, we will explore the various ways to check if a variable is undefined in JavaScript and discuss the best practices for handling undefined variables in your code. We will also provide some practical examples to demonstrate how to implement these methods in your code. By the end of this article, you will have a solid understanding of how to check for undefined variables in JavaScript and how to write more robust and error-free code.

Using the === Operator to check if value is undefined

The === operator is used to check if two values are strictly equal. It returns true if the values are equal and of the same data type. Therefore, we can use the === operator to check if a value is undefined, as follows:

Here is a simple structure of how to use the === operator in checking if value is undefined

Now, let’s check if a undefined variable is undefined using the === operator in combination with the if statement.

Now, let’s try the same code with a defined variable, and let’s see the output

In the first example, the variable x is declared but not assigned a value. Therefore, it is assigned the value of undefined. The if statement checks if x is undefined and logs a message to the console if it is. In the second example, the variable y is assigned a value of 0. Therefore, the if statement does not execute since y is not undefined, but the added else statement is executed and logs the message within the block.

Using the typeof Operator to check if variable is undefined

The typeof operator is used to determine the data type of a value. It returns a string indicating the data type of the operand. When used with an uninitialized variable, it returns "undefined". Therefore, we can use the typeof operator to check if a variable is undefined, as follows:

Here is the simple syntax structure to check if variable is undefined using the typeof operator.

Now, let’s illustrate how we could use the typeof operator and if/else statement to check if variable is undefined.

In another example, we pass a null value to a variable, and we illustrate if the variable is undefined or not.

In first example, the variable a is declared but not assigned a value. The typeof operator returns "undefined", and the if statement logs a message to the console. For the other example, the variable b is assigned a value of null. Therefore, the if statement does not execute since b is not undefined and the else statement is executed.

Using the negation operator (!) to check if variable is undefined

Using the negation operator (!) with a variable is a commonly used method to check if a variable is undefined in JavaScript. When the negation operator is applied to a variable, it first coerces the variable to a boolean value and then negates it. If the variable is undefined, it is coerced to a falsy value, and the negation operator returns true. Otherwise, if the variable is defined, it is coerced to a truthy value, and the negation operator returns false.

Here's an example:

In this example, the variable variableName is not assigned a value, so it is undefined. When the negation operator is applied to it in the if statement, it returns true, and the message "The variable is undefined" is printed to the console.

One advantage of using the negation operator is that it provides a concise way of checking if a variable is undefined. However, it is important to note that it can produce unexpected results if the variable is assigned a falsy value, such as false , 0 , or an empty string. In such cases, the negation operator would incorrectly indicate that the variable is undefined. Therefore, it is important to use this method with caution and ensure that the variable is truly undefined before using the negation operator to check it.

Optional chaining '?.'

The optional chaining ?. is a safe way to access nested object properties, even if an intermediate property doesn’t exist.

The “non-existing property” problem

If you’ve just started to read the tutorial and learn JavaScript, maybe the problem hasn’t touched you yet, but it’s quite common.

As an example, let’s say we have user objects that hold the information about our users.

Most of our users have addresses in user.address property, with the street user.address.street , but some did not provide them.

In such case, when we attempt to get user.address.street , and the user happens to be without an address, we get an error:

That’s the expected result. JavaScript works like this. As user.address is undefined , an attempt to get user.address.street fails with an error.

In many practical cases we’d prefer to get undefined instead of an error here (meaning “no street”).

…and another example. In Web development, we can get an object that corresponds to a web page element using a special method call, such as document.querySelector('.elem') , and it returns null when there’s no such element.

Once again, if the element doesn’t exist, we’ll get an error accessing .innerHTML property of null . And in some cases, when the absence of the element is normal, we’d like to avoid the error and just accept html = null as the result.

How can we do this?

The obvious solution would be to check the value using if or the conditional operator ? , before accessing its property, like this:

It works, there’s no error… But it’s quite inelegant. As you can see, the "user.address" appears twice in the code.

Here’s how the same would look for document.querySelector :

We can see that the element search document.querySelector('.elem') is actually called twice here. Not good.

For more deeply nested properties, it becomes even uglier, as more repetitions are required.

E.g. let’s get user.address.street.name in a similar fashion.

That’s just awful, one may even have problems understanding such code.

There’s a little better way to write it, using the && operator:

AND’ing the whole path to the property ensures that all components exist (if not, the evaluation stops), but also isn’t ideal.

As you can see, property names are still duplicated in the code. E.g. in the code above, user.address appears three times.

That’s why the optional chaining ?. was added to the language. To solve this problem once and for all!

Optional chaining

The optional chaining ?. stops the evaluation if the value before ?. is undefined or null and returns undefined .

Further in this article, for brevity, we’ll be saying that something “exists” if it’s not null and not undefined .

In other words, value?.prop :

  • works as value.prop , if value exists,
  • otherwise (when value is undefined/null ) it returns undefined .

Here’s the safe way to access user.address.street using ?. :

The code is short and clean, there’s no duplication at all.

Here’s an example with document.querySelector :

Reading the address with user?.address works even if user object doesn’t exist:

Please note: the ?. syntax makes optional the value before it, but not any further.

E.g. in user?.address.street.name the ?. allows user to safely be null/undefined (and returns undefined in that case), but that’s only for user . Further properties are accessed in a regular way. If we want some of them to be optional, then we’ll need to replace more . with ?. .

We should use ?. only where it’s ok that something doesn’t exist.

For example, if according to our code logic user object must exist, but address is optional, then we should write user.address?.street , but not user?.address?.street .

Then, if user happens to be undefined, we’ll see a programming error about it and fix it. Otherwise, if we overuse ?. , coding errors can be silenced where not appropriate, and become more difficult to debug.

If there’s no variable user at all, then user?.anything triggers an error:

The variable must be declared (e.g. let/const/var user or as a function parameter). The optional chaining works only for declared variables.

Short-circuiting

As it was said before, the ?. immediately stops (“short-circuits”) the evaluation if the left part doesn’t exist.

So, if there are any further function calls or operations to the right of ?. , they won’t be made.

For instance:

Other variants: ?.(), ?.[]

The optional chaining ?. is not an operator, but a special syntax construct, that also works with functions and square brackets.

For example, ?.() is used to call a function that may not exist.

In the code below, some of our users have admin method, and some don’t:

Here, in both lines we first use the dot ( userAdmin.admin ) to get admin property, because we assume that the user object exists, so it’s safe read from it.

Then ?.() checks the left part: if the admin function exists, then it runs (that’s so for userAdmin ). Otherwise (for userGuest ) the evaluation stops without errors.

The ?.[] syntax also works, if we’d like to use brackets [] to access properties instead of dot . . Similar to previous cases, it allows to safely read a property from an object that may not exist.

Also we can use ?. with delete :

The optional chaining ?. has no use on the left side of an assignment.

For example:

The optional chaining ?. syntax has three forms:

  • obj?.prop – returns obj.prop if obj exists, otherwise undefined .
  • obj?.[prop] – returns obj[prop] if obj exists, otherwise undefined .
  • obj.method?.() – calls obj.method() if obj.method exists, otherwise returns undefined .

As we can see, all of them are straightforward and simple to use. The ?. checks the left part for null/undefined and allows the evaluation to proceed if it’s not so.

A chain of ?. allows to safely access nested properties.

Still, we should apply ?. carefully, only where it’s acceptable, according to our code logic, that the left part doesn’t exist. So that it won’t hide programming errors from us, if they occur.

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

How the Question Mark (?) Operator Works in JavaScript

The conditional or question mark operator, represented by a ? , is one of the most powerful features in JavaScript. The ? operator is used in conditional statements, and when paired with a : , can function as a compact alternative to if...else statements.

But there is more to it than meets the eye. There are three main uses for the ? operator, two of which you might not used or even heard of. Let's learn about them all in detail.

Three Main Uses for the Question Mark ( ? ) in JavaScript:

  • Ternary Operator
  • Optional Chaining
  • Nullish Coalescing

We'll look at each of these in detail, starting with the most common way you'll see the ? operator being used – as a ternary operator.

1. Ternary Operator

The term ternary means composed of three items or parts. The ? operator is also called the ternary operator because, unlike other operators such as strict equal ( === ) or remainder ( % ), it's the only one that takes three operands.

Starting with ? , we add a condition on the left side and a value on the right side to return when the condition is true. Then we add a colon ( : ) followed by a value to return if the condition is false.

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--1-

The ternary operator is basically a shortcut for a traditional if...else statement.

Let's compare a ternary operator with a longer if...else statement:

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--22-

Here, the ternary operator occupies only one line of code, whereas the if...else takes seven lines.

Using a ternary operator is much more effective, right?

2. Optional Chaining

In 2020, an awesome new feature known as Optional Chaining was introduced.

To understand how it works, imagine this scenario.

Let's say you have code that calls on an object property that doesn't exist, which triggers an error at run time. This may be because of a missing or undefined value in your database or from an API:

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--23--2

Thanks to Optional Chaining, you can just insert a ? between the property name and the period between the next property.

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--24-

With that, it will just return undefined instead of throwing an ugly error.

Optional Chaining is truly a life-changing feature for JavaScript developers.

3. Nullish Coalescing

In some cases, you have to set a default value for a missing property name or value.

For example, let's say we are creating a Weather App in which we are fetching the temperature, humidity, wind speed, pressure, time of sunrise and sunset, and the picture of the city. We inputted a place, let's say Bangalore , but for some reason, its image is not there in the database.

When the app fetches and displays the data, the picture will be blank, which can look ugly. What we can do, in that case, is set a default picture for those cities which don't have an image, Bangalore in our case.

This way, when the app displays the data, the default picture will be there for the cities without images.

You can do this using the || operator, known as the logical OR operator:

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--4-

But if you use || to provide a default value, you may encounter unexpected behaviors if you consider some values as usable (for example, '' or 0 ).

Consider a scenario where a variable has the value of 0 or an empty string. If we use ( || ), it will be considered as undefined or NULL and return some default value that we have fixed.

Instead of the logical OR ( || ) operator, you can use double question marks ( ?? ), or Nullish Coalescing.

Let's learn with an example.

Here, we have '0' and 'default string' in variable value1. If we log its value in the console, we will get 'default string', which is weird. Instead of the default string, we should be getting 0, as zero is not undefined or null. So, ' || ' fails to do the job here.

Similarly, it's the same with value2.

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--25-

But if we replace ' || ' with ' ?? ', we will get 0 and an empty string, which makes it so cool.

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--26-

Nullish Coalescing works exactly like the logical OR operator, except you will get the right side value when the left side value is undefined or null .

In other words, ?? only allows undefined and null values, not empty strings ( '' ) or 0 s.

Now hopefully you understand how the ? operator works in JavaScript. It looks simple, but it's one of the most powerful characters in the language. It provides syntactic sugar in three awesome but different ways.

Try them them out and let me know how it goes.

Happy learning!

I build projects to learn how code works. And while I am not coding, I enjoy writing poetry and stories, playing the piano, and cooking delicious meals.

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

IMAGES

  1. JavaScript Conditional Statements

    javascript conditional operator undefined

  2. Javascript Tutorial -9- Conditional Operators

    javascript conditional operator undefined

  3. What is a Conditional Statement in JavaScript or a Desicion Statement?

    javascript conditional operator undefined

  4. Conditional Operator in JavaScript

    javascript conditional operator undefined

  5. JavaScript Training Tutorial Conditional Operator

    javascript conditional operator undefined

  6. Javascript conditional operator or ternary operator

    javascript conditional operator undefined

VIDEO

  1. JavaScript Conditional Statement if,else and else if✅

  2. JavaScript Conditional Control Statements 3

  3. 3. Data types & typeof operator in javascript

  4. DAY-52 JS String, Boolean, Null, Undefined, Array

  5. Mastering Conditional Rendering in ReactJS: Building Dynamic User Interfaces

  6. JavaScript Conditional Statement Tutorial Part 8

COMMENTS

  1. Conditional (ternary) operator

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

  2. Javascript undefined condition

    Javascript undefined condition Ask Question Asked 12 years, 5 months ago Modified 3 years, 8 months ago Viewed 34k times 6 Could somebody explain to me the difference between if (obj.x == undefined) and if (typeof obj.x == 'undefined') In some context the first one works fine, but in other I need to use the second way. Questions

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

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

  4. Conditional (ternary) Operator

    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: 'The fee is ' + (isMember ? '$2.00' : '$10.00'); You can also assign variables depending on a ternary result:

  5. Conditional (ternary) operator

    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 x 1 function getFee(isMember) { 2 return (isMember ? "$2.00" : "$10.00"); 3 }

  6. A definitive guide to conditional logic in JavaScript

    There are only six falsy values in JavaScript — false, null, undefined, NaN, 0, and "" — and everything else is truthy. This means that [] and {} are both truthy, which tend to trip people up. The logical operators. In formal logic, only a few operators exist: negation, conjunction, disjunction, implication, and bicondition.

  7. JavaScript Comparison and Logical Operators

    JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax variablename = ( condition) ? value1: value2 Example let voteable = (age < 18) ? "Too young":"Old enough"; Try it Yourself »

  8. Operators

    Conditional Operator. condition ? expression : expression. 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. ... Undefined "undefined" Boolean "boolean" Number "number" String "string" Symbol (ES6) "symbol"

  9. How to check if undefined in JavaScript? [SOLVED]

    Using the ternary operator is another method to check if a variable is undefined in JavaScript. The ternary operator provides a concise way of writing conditional statements and is commonly used in JavaScript to check if a variable is defined. ALSO READ. Solved: Get current directory in Node.js [4 Examples]

  10. JavaScript Check if Undefined

    How to Check if a Variable is Undefined in JavaScript with the Void Operator. The void operator is often used to obtain the undefined primitive value. You can do this using "void(0)" which is similar to "void 0" as you can see below: console.log(void 0); // undefined console.log(void(0)); // undefined In the actual sense, this works like direct ...

  11. Optional chaining

    The obvious solution would be to check the value using if or the conditional operator ?, before accessing its property, like this: let user = {}; alert( user. address ? user. address. street : undefined); It works, there's no error… But it's quite inelegant. As you can see, the "user.address" appears twice in the code.

  12. How the Question Mark (?) Operator Works in JavaScript

    This may be because of a missing or undefined value in your database or from an API: A common error - TypeError: Cannot read property 'salary' of undefined Thanks to Optional Chaining, you can just insert a ? between the property name and the period between the next property.

  13. javascript

    javascript - How to check undefined variable in a ternary operator? - Stack Overflow How to check undefined variable in a ternary operator? Ask Question Asked 6 years ago Modified 4 years ago Viewed 49k times 21 I have an issue with ternary operation: let a = undefined ? "Defined!" : "Definitely Undefined", b = abc ? "Defined!"

  14. TopDev

    34 likes, 0 comments - topdev_media on February 4, 2024: " JavaScript Trick - #5 ‍ Hello fellow JavaScript enthusiasts! Get ready to simpli..." TopDev - Coding - Web development on Instagram: "🚀 JavaScript Trick - #5 👨‍💻 Hello fellow JavaScript enthusiasts!

  15. javascript

    1 I have a fn that creates and populate variable linkedinInsight when its invoked. Just a quick overview of this fn, it will check the response data and see if there is a match. If yes, it would populate the linkedinInight variable with the data.