How to Use the Ternary Operator in JavaScript – JS Conditional Example

Dionysia Lemonaki

The ternary operator is a helpful feature in JavaScript that allows you to write concise and readable expressions that perform conditional operations on only one line.

In this article, you will learn why you may want to use the ternary operator, and you will see an example of how to use it. You will also learn some of the best practices to keep in mind when you do use it.

Let's get into it!

What Is The Ternary Operator in JavaScript?

The ternary operator ( ?: ), also known as the conditional operator, is a shorthand way of writing conditional statements in JavaScript – you can use a ternary operator instead of an if..else statement.

A ternary operator evaluates a given condition, also known as a Boolean expression, and returns a result that depends on whether that condition evaluates to true or false .

Why Use the Ternary Operator in JavaScript?

You may want to use the ternary operator for a few reasons:

  • Your code will be more concise : The ternary operator has minimal syntax. You will write short conditional statements and fewer lines of code, which makes your code easier to read and understand.
  • Your code will be more readable : When writing simple conditions, the ternary operator makes your code easier to understand in comparison to an if..else statement.
  • Your code will be more organized : The ternary operator will make your code more organized and easier to maintain. This comes in handy when writing multiple conditional statements. The ternary operator will reduce the amount of nesting that occurs when using if..else statements.
  • It provides flexibility : The ternary operator has many use cases, some of which include: assigning a value to a variable, rendering dynamic content on a web page, handling function arguments, validating data and handling errors, and creating complex expressions.
  • It enhances performance : In some cases, the ternary operator can perform better than an if..else statement because the ternary operator gets evaluated in a single step.
  • It always returns a value : The ternary operator always has to return something.

How to Use the Ternary Operator in JavaScript – a Syntax Overview

The operator is called "ternary" because it is composed of three parts: one condition and two expressions.

The general syntax for the ternary operator looks something similar to the following:

Let's break it down:

  • condition is the Boolean expression you want to evaluate and determine whether it is true or false . The condition is followed by a question mark, ? .
  • ifTrueExpression is executed if the condition evaluates to true .
  • ifFalseExpression is executed if the condition evaluates to false .
  • The two expressions are separated by a colon, . .

The ternary operator always returns a value that you assign to a variable:

Next, let's look at an example of how the ternary operator works.

How to Use the Ternary Operator in JavaScript

Say that you want to check whether a user is an adult:

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.

Next, the condition ( age >= 18 ) gets evaluated.

If the condition is true , the first expression, You are an adult , gets executed.

Say the user enters the value 18 .

The condition age >= 18 evaluates to true :

If the condition is false , the second expression, You are not an adult yet , gets executed.

Say the user enters the value 17 .

The condition age >= 18 now evaluates to false :

As mentioned earlier, you can use the ternary operator instead of an if..else statement.

Here is how you would write the same code used in the example above using an if..else statement:

Ternary Operator Best Practices in JavaScript

Something to keep in mind when using the ternary operator is to keep it simple and don't overcomplicate it.

The main goal is for your code to be readable and easily understandable for the rest of the developers on your team.

So, consider using the ternary operator for simple statements and as a concise alternative to if..else statements that can be written in one line.

If you do too much, it can quickly become unreadable.

For example, in some cases, using nested ternary operators can make your code hard to read:

If you find yourself nesting too many ternary operators, consider using if...else statements instead.

Conditional branching: if, '?'

Sometimes, we need to perform different actions based on different conditions.

To do that, we can use the if statement and the conditional operator ? , that’s also called a “question mark” operator.

The “if” statement

The if(...) statement evaluates a condition in parentheses and, if the result is true , executes a block of code.

For example:

In the example above, the condition is a simple equality check ( year == 2015 ), but it can be much more complex.

If we want to execute more than one statement, we have to wrap our code block inside curly braces:

We recommend wrapping your code block with curly braces {} every time you use an if statement, even if there is only one statement to execute. Doing so improves readability.

Boolean conversion

The if (…) statement evaluates the expression in its parentheses and converts the result to a boolean.

Let’s recall the conversion rules from the chapter Type Conversions :

  • A number 0 , an empty string "" , null , undefined , and NaN all become false . Because of that they are called “falsy” values.
  • Other values become true , so they are called “truthy”.

So, the code under this condition would never execute:

…and inside this condition – it always will:

We can also pass a pre-evaluated boolean value to if , like this:

The “else” clause

The if statement may contain an optional else block. It executes when the condition is falsy.

Several conditions: “else if”

Sometimes, we’d like to test several variants of a condition. The else if clause lets us do that.

In the code above, JavaScript first checks year < 2015 . If that is falsy, it goes to the next condition year > 2015 . If that is also falsy, it shows the last alert .

There can be more else if blocks. The final else is optional.

Conditional operator ‘?’

Sometimes, we need to assign a variable depending on a condition.

For instance:

The so-called “conditional” or “question mark” operator lets us do that in a shorter and simpler way.

The operator is represented by a question mark ? . Sometimes it’s called “ternary”, because the operator has three operands. It is actually the one and only operator in JavaScript which has that many.

The syntax is:

The condition is evaluated: if it’s truthy then value1 is returned, otherwise – value2 .

Technically, we can omit the parentheses around age > 18 . The question mark operator has a low precedence, so it executes after the comparison > .

This example will do the same thing as the previous one:

But parentheses make the code more readable, so we recommend using them.

In the example above, you can avoid using the question mark operator because the comparison itself returns true/false :

Multiple ‘?’

A sequence of question mark operators ? can return a value that depends on more than one condition.

It may be difficult at first to grasp what’s going on. But after a closer look, we can see that it’s just an ordinary sequence of tests:

  • The first question mark checks whether age < 3 .
  • If true – it returns 'Hi, baby!' . Otherwise, it continues to the expression after the colon “:”, checking age < 18 .
  • If that’s true – it returns 'Hello!' . Otherwise, it continues to the expression after the next colon “:”, checking age < 100 .
  • If that’s true – it returns 'Greetings!' . Otherwise, it continues to the expression after the last colon “:”, returning 'What an unusual age!' .

Here’s how this looks using if..else :

Non-traditional use of ‘?’

Sometimes the question mark ? is used as a replacement for if :

Depending on the condition company == 'Netscape' , either the first or the second expression after the ? gets executed and shows an alert.

We don’t assign a result to a variable here. Instead, we execute different code depending on the condition.

It’s not recommended to use the question mark operator in this way.

The notation is shorter than the equivalent if statement, which appeals to some programmers. But it is less readable.

Here is the same code using if for comparison:

Our eyes scan the code vertically. Code blocks which span several lines are easier to understand than a long, horizontal instruction set.

The purpose of the question mark operator ? is to return one value or another depending on its condition. Please use it for exactly that. Use if when you need to execute different branches of code.

if (a string with zero)

Will alert be shown?

Yes, it will.

Any string except an empty one (and "0" is not empty) becomes true in the logical context.

We can run and check:

The name of JavaScript

Using the if..else construct, write the code which asks: ‘What is the “official” name of JavaScript?’

If the visitor enters “ECMAScript”, then output “Right!”, otherwise – output: “You don’t know? ECMAScript!”

Demo in new window

Show the sign

Using if..else , write the code which gets a number via prompt and then shows in alert :

  • 1 , if the value is greater than zero,
  • -1 , if less than zero,
  • 0 , if equals zero.

In this task we assume that the input is always a number.

Rewrite 'if' into '?'

Rewrite this if using the conditional operator '?' :

Rewrite 'if..else' into '?'

Rewrite if..else using multiple ternary operators '?' .

For readability, it’s recommended to split the code into multiple lines.

  • 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

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
  • Conditional Statements in Java
  • If-Then and If-Then-Else Conditional Statements in Java
  • What Are Ternary (Conditional) Operators in Ruby?
  • JavaScript Nested IF/ELSE Statements
  • The If-Then-Else Statement in Delphi Code
  • Conditional Operators
  • How to Return a Value in JavaScript
  • Using the Case (Switch) Ruby Statement
  • Control Statements in C++
  • Understanding and Using Loops in Delphi Programming
  • Java Expressions Introduced
  • Using the Switch Statement for Multiple Choices in Java
  • How to Use Loops in Ruby
  • How to Create a Continuous Text Marquee in JavaScript
  • How to Create a Continuous Image Marquee With JavaScript
  • Skip to main content
  • Select language
  • Skip to search
  • Assignment operators

An assignment operator assigns a value to its left operand based on the value of its right operand.

The basic assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x . The other assignment operators are usually shorthand for standard operations, as shown in the following definitions and examples.

Simple assignment operator which assigns a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables. See the example.

Addition assignment

The addition assignment operator adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible. See the addition operator for more details.

Subtraction assignment

The subtraction assignment operator subtracts the value of the right operand from a variable and assigns the result to the variable. See the subtraction operator for more details.

Multiplication assignment

The multiplication assignment operator multiplies a variable by the value of the right operand and assigns the result to the variable. See the multiplication operator for more details.

Division assignment

The division assignment operator divides a variable by the value of the right operand and assigns the result to the variable. See the division operator for more details.

Remainder assignment

The remainder assignment operator divides a variable by the value of the right operand and assigns the remainder to the variable. See the remainder operator for more details.

Exponentiation assignment

This is an experimental technology, part of the ECMAScript 2016 (ES7) proposal. Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.

The exponentiation assignment operator evaluates to the result of raising first operand to the power second operand. See the exponentiation operator for more details.

Left shift assignment

The left shift assignment operator moves the specified amount of bits to the left and assigns the result to the variable. See the left shift operator for more details.

Right shift assignment

The right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the right shift operator for more details.

Unsigned right shift assignment

The unsigned right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the unsigned right shift operator for more details.

Bitwise AND assignment

The bitwise AND assignment operator uses the binary representation of both operands, does a bitwise AND operation on them and assigns the result to the variable. See the bitwise AND operator for more details.

Bitwise XOR assignment

The bitwise XOR assignment operator uses the binary representation of both operands, does a bitwise XOR operation on them and assigns the result to the variable. See the bitwise XOR operator for more details.

Bitwise OR assignment

The bitwise OR assignment operator uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable. See the bitwise OR operator for more details.

Left operand with another assignment operator

In unusual situations, the assignment operator (e.g. x += y ) is not identical to the meaning expression (here x = x + y ). When the left operand of an assignment operator itself contains an assignment operator, the left operand is evaluated only once. For example:

Specifications

Browser compatibility.

  • Arithmetic operators

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()
  • Array comprehensions
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • 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 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

Tania Rascia

JavaScript Operators, Conditionals & Functions

Share this article

JavaScript Operators, Conditionals & Functions

JavaScript Operators

Conditional statements, frequently asked questions (faqs) about javascript operators, conditionals, and functions.

  • Arithmetic Operators: Perform operations and manipulate data. For example, the addition operator (+) can be used to add two numbers together.
  • Comparison Operators: Compare two or more values and return a boolean value (true or false) For example, using the greater than (>) operator to check if an integer variable is larger than another.
  • Logical Operators: Used to connect two or more comparison operators and return a boolean value. For example, using the AND operator (&&) to see if a variable is between two values, i.e. that it is larger than one number and smaller the other.
  • Conditional statements: Control the flow of a program based on certain conditions. For example, an if statement can be used to execute a block of code only if a certain condition is met.
  • Functions: Encapsulate a set of statements to be used multiple times, making code more organized and reusable. Functions can also accept inputs and return outputs, allowing for more dynamic and flexible code.

Table of Contents

Assignment operators, subtraction, multiplication, strict equal, strict not equal, less than or equal to, greater than, greater than or equal to, operator precedence, declaration, parameters and arguments.

Disclaimer: This guide is intended for complete beginners to JavaScript and programming. As such, many concepts will be presented in a simplified manner.

Arithmetic Operators

Comparison operators, logical operators.

  • Grouping ( () )
  • Multiplication ( * )
  • Division ( / )
  • Modulus ( % )
  • Addition ( + )
  • Subtraction ( - )
  • Less than ( < )
  • Less than or equal ( <= )
  • Greater than ( > )
  • Greater than or equal ( >= )
  • Equal ( = )
  • Not equal ( != )
  • Strict equal ( === )
  • Strict not equal ( !== )
  • And ( && )
  • Assignment ( = )
A local variable is a variable that will only work inside a specific code block.

What is the significance of operator precedence in JavaScript?

Operator precedence in JavaScript determines the way operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence. Understanding operator precedence is crucial as it helps to predict the outcome of an operation. For instance, multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-). Therefore, in an expression like 2 + 3 * 4, the multiplication happens first, resulting in 2 + 12 = 14, not 20.

How can I change the order of operations in JavaScript?

You can change the order of operations in JavaScript by using parentheses. The expressions inside parentheses are evaluated first. For example, in the expression (2 + 3) * 4, the addition operation is performed first because it’s inside the parentheses, resulting in 5 * 4 = 20.

What are conditional statements in JavaScript?

Conditional statements in JavaScript are used to perform different actions based on different conditions. The most common conditional statements are if, else if, and else. These statements allow the program to make decisions and execute the appropriate code block based on the condition’s truthiness.

How do JavaScript functions work?

Functions in JavaScript are blocks of code designed to perform a particular task. A JavaScript function is executed when something invokes it (calls it). Functions can be defined using the function keyword, followed by a name, and parentheses (). The code to be executed by the function is placed inside curly brackets {}.

What are the different types of operators in JavaScript?

JavaScript includes various types of operators such as arithmetic operators (+, -, *, /, %, ++, –), assignment operators (=, +=, -=, *=, /=, %=), comparison operators (==, ===, !=, !==, >, <, >=, <=), logical operators (&&, ||, !), and bitwise operators (&, |, ^, ~, <<, >>, >>>).

How does the ternary operator work in JavaScript?

The ternary operator is a shorthand way of writing an if-else statement. It’s called the ternary operator because it takes three operands – a condition, a result for true, and a result for false. For example, the code let result = (a > b) ? ‘a is greater’ : ‘b is greater’; will assign the string ‘a is greater’ to the result if a is greater than b, and ‘b is greater’ if a is not greater than b.

What is the difference between == and === operators in JavaScript?

The == operator checks for equality in value but not type. It performs type coercion if the variables being compared are not of the same type. On the other hand, the === operator, also known as the strict equality operator, checks for both value and type. It does not perform type coercion, so if the variables being compared are not of the same type, it will return false.

How can I define a function in JavaScript?

A function in JavaScript can be defined using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. For example, function myFunction(parameter1, parameter2) { // code to be executed }.

What are JavaScript logical operators?

JavaScript logical operators are used to determine the logic between variables or values. The three logical operators are AND (&&), OR (||), and NOT (!). The AND operator returns true if both operands are true, the OR operator returns true if at least one operand is true, and the NOT operator returns the inverse of the given boolean value.

How does the switch statement work in JavaScript?

The switch statement in JavaScript is used to perform different actions based on different conditions. It’s a more efficient way to code when dealing with many conditions. The switch expression is evaluated once, and its value is compared with the values of each case. If there’s a match, the associated block of code is executed.

A web developer from Chicago who blogs about code and design, and enjoys losing at Age of Empires 2 in her spare time.

SitePoint Premium

  • 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 Continue Statement
  • Garbage Collection in JavaScript
  • Introduction to Three.js
  • Synchronous and Asynchronous in JavaScript
  • JavaScript Label Statement
  • JavaScript | DataView()
  • Javascript Error and Exceptional Handling With Examples
  • Dynamic User Interfaces in JavaScript
  • Control Statements in JavaScript
  • JavaScript Loops
  • Global and Local variables in JavaScript
  • Static Methods in JavaScript
  • JavaScript Versions
  • JavaScript Variables
  • Difference Between Variables and Objects in JavaScript
  • Interesting Facts About Javascript
  • Top 7 One liners of JavaScript
  • JavaScript Code Execution
  • JavaScript SyntaxError - A declaration in the head of a for-of loop can't have an initializer

Conditional Statements in JavaScript

JavaScript Conditional statements allow you to execute specific blocks of code based on conditions. If the condition meets then a particular block of action will be executed otherwise it will execute another block of action that satisfies that particular condition.

There are several methods that can be used to perform Conditional Statements in JavaScript.

  • if statement : Executes a block of code if a specified condition is true.
  • else statement : Executes a block of code if the same condition of the preceding if statement is false.
  • else if statement : Adds more conditions to the if statement, allowing for multiple alternative conditions to be tested.
  • switch statement : Evaluates an expression, then executes the case statement that matches the expression’s value.
  • ternary operator (conditional operator) : Provides a concise way to write if-else statements in a single line.

JavaScript Conditional statements Examples:

1. using if statement.

The if statement is used to evaluate a particular condition. If the condition holds true, the associated code block is executed.

Example: In this example, we are using the if statement to find given number is even or odd.

Explanation: This JavaScript code determines if the variable `num` is even or odd using the modulo operator `%`. If `num` is divisible by 2 without a remainder, it logs “Given number is even number.” Otherwise, it logs “Given number is odd number.”

2. Using if-else Statement

The if-else statement will perform some action for a specific condition. Here we are using the else statement in which the else statement is written after the if statement and it has no condition in their code block.

Example: In this example, we are using if-else conditional statement to check the driving licence eligibility date.

Explanation: This JavaScript code checks if the variable `age` is greater than or equal to 18. If true, it logs “You are eligible for a driving license.” Otherwise, it logs “You are not eligible for a driving license.” This indicates eligibility for driving based on age.

3. else if Statement

The else if statement in JavaScript allows handling multiple possible conditions and outputs, evaluating more than two options based on whether the conditions are true or false.

Example: In this example, we are using the above-explained approach.

Explanation: This JavaScript code determines whether the constant `num` is positive, negative, or zero. If `num` is greater than 0, it logs “Given number is positive.” If `num` is less than 0, it logs “Given number is negative.” If neither condition is met (i.e., `num` is zero), it logs “Given number is zero.”

4. Using Switch Statement (JavaScript Switch Case)

As the number of conditions increases, you can use multiple else-if statements in JavaScript. but when we dealing with many conditions, the switch statement may be a more preferred option.

Example: In this example, we find a branch name Based on the student’s marks, this switch statement assigns a specific engineering branch to the variable Branch. The output displays the student’s branch name,

Explanation:

This JavaScript code assigns a branch of engineering to a student based on their marks. It uses a switch statement with cases for different mark ranges. The student’s branch is determined according to their marks and logged to the console.

5. Using Ternary Operator ( ?: )

The conditional operator, also referred to as the ternary operator (?:), is a shortcut for expressing conditional statements in JavaScript.

Example: In this example, we use the ternary operator to check if the user’s age is 18 or older. It prints eligibility for voting based on the condition.

Explanation: This JavaScript code checks if the variable `age` is greater than or equal to 18. If true, it assigns the string “You are eligible to vote.” to the variable `result`. Otherwise, it assigns “You are not eligible to vote.” The value of `result` is then logged to the console.

Conditional Statements in JavaScript Use-Cases:

1. javascript if-else.

JavaScript  if-else  or conditional statements will perform some action for a specific condition.

2. Control Statements in JavaScript

Control Statements are used to control the flow of the program with the help of conditional statements.

Please Login to comment...

Similar reads.

  • javascript-basics
  • Web Technologies
  • Google Introduces New AI-powered Vids App
  • Dolly Chaiwala: The Microsoft Windows 12 Brand Ambassador
  • 10 Best Free Remote Desktop apps for Android in 2024
  • 10 Best Free Internet Speed Test apps for Android in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. JavaScript Conditional Statements

    javascript conditional variable assignment

  2. JavaScript Tutorial

    javascript conditional variable assignment

  3. Conditional Statements in JavaScript

    javascript conditional variable assignment

  4. Javascript #3

    javascript conditional variable assignment

  5. JavaScript Conditional Statements Tutorial with Example

    javascript conditional variable assignment

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

    javascript conditional variable assignment

VIDEO

  1. Basic JavaScript Declare JavaScript Variables freeCodeCamp

  2. JavaScript var let const Variable Keyword

  3. Javascript

  4. Javascript Variables

  5. JavaScript Conditional Statement

  6. Javascript Conditional and Assignment Operators Explained in Tamil

COMMENTS

  1. Best Way for Conditional Variable Assignment

    There are two methods I know of that you can declare a variable's value by conditions. Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into ...

  2. Conditional (ternary) operator

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

  3. Making decisions in your code

    Here we've got: The keyword switch, followed by a set of parentheses.; An expression or value inside the parentheses. The keyword case, followed by a choice that the expression/value could be, followed by a colon.; Some code to run if the choice matches the expression. A break statement, followed by a semicolon. If the previous choice matches the expression/value, the browser stops executing ...

  4. How to Use the Ternary Operator in JavaScript

    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. Next, the condition (age >= 18) gets evaluated. If the condition is true, the first expression, You are an adult, gets executed. Say the user ...

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

    It can be used to assign a value to a variable based on a condition, or execute an expression based on a condition. Syntax The ternary operator accepts three operands; it's the only operator in ...

  6. Conditional branching: if,

    In the code above, JavaScript first checks year < 2015. If that is falsy, it goes to the next condition year > 2015. If that is also falsy, it shows the last alert. There can be more else if blocks. The final else is optional. Conditional operator '?' Sometimes, we need to assign a variable depending on a condition. For instance:

  7. Conditional (ternary) Operator

    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:

  8. Expressions and operators

    This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that ...

  9. if...else

    statement1. [else. statement2 ] condition. An expression that is considered to be either truthy or falsy. statement1. Statement that is executed if condition is truthy. Can be any statement, including further nested if statements.

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

    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:

  11. Variable assignment inside an 'if' condition in JavaScript

    To understand what is going on, refer to the operator precedence and associativity chart.The expression a = 2 && (b = 8) is evaluated as follows: && operator is evaluated before = since it has higher priority the left hand expression 2 is evaluated which is truthy; the right hand expression b = 8 is evaluated (b becomes 8 and 8 is returned); 8 is returned; a = 8 is evaluated (a becomes 8 and 8 ...

  12. JavaScript Conditionals: The Basics with Examples

    The keyword if tells JavaScript to start the conditional statement. (10 > 5) is the condition to test, which in this case is true — 10 is greater than 5. The part contained inside curly braces {} is the block of code to run. Because the condition passes, the variable outcome is assigned the value "if block".

  13. Assignment operators

    The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables. See the example. Syntax Operator: x = y Examples // Assuming the following variables // x = 5 // y = 10 // z = 25 x = y // x is 10 x = y = z // x, y and z are all 25 Addition assignment

  14. JavaScript Operators, Conditionals & Functions

    In this article, we learned three very important fundamental concepts of JavaScript: operators, conditional statements, and functions. Operators are symbols that perform operations on data, and we ...

  15. Conditional Statements in JavaScript

    Explanation: This JavaScript code determines whether the constant `num` is positive, negative, or zero. If `num` is greater than 0, it logs "Given number is positive.". If `num` is less than 0, it logs "Given number is negative.". If neither condition is met (i.e., `num` is zero), it logs "Given number is zero.". 4.

  16. javascript

    A very easy typescript question, which I need assistance with. Without using if statements, how would I conditional assign something to a constant variable. const myConstant = myProduct.productId; I want it so that if the productId in myProduct is empty (""), it will assign the variable of myConstant to "No Product", I wish to do this without ...

  17. JavaScript OR (||) variable assignment explanation

    This is made to assign a default value, in this case the value of y, if the x variable is falsy. The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages. The Logical OR operator ( ||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first ...

  18. Optional chaining (?.)

    You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device. Using optional chaining with function calls causes the ...

  19. Assignment (=)

    Assignment (=) The assignment ( =) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

  20. setting a javascript variable with an if statement -- should the 'var

    Switch to CoffeeScript (which compiles to JavaScript). Then you can do: B = if A == "red" then "hot" else "cool" Everything in CoffeeScript is an expression! So you can assign the value of a switch statement to a variable too: B = switch A when "red" then "hot" when "blue" then "cool" else "medium"

  21. Logical OR assignment (||=)

    Description. Logical OR assignment short-circuits, meaning that x ||= y is equivalent to x || (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const: js.