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.

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy
  • 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

Conditional Statements in JavaScript

JavaScript conditional statements allow you to execute specific blocks of code based on conditions. If the condition is met, a particular block of code will run; otherwise, another block of code will execute based on the condition.

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

Conditional StatementDescription
if statementExecutes a block of code if a specified condition is true.
else statementExecutes a block of code if the same condition of the preceding if statement is false.
else if statementAdds more conditions to the if statement, allowing for multiple alternative conditions to be tested.
switch statementEvaluates an expression, then executes the case statement that matches the expression’s value.
ternary operatorProvides a concise way to write if-else statements in a single line.
Nested if else statementAllows for multiple conditions to be checked in a hierarchical manner.

This table outlines the key characteristics and use cases of each type of conditional statement. Now let’s understand each conditional statement in detail along with the examples.

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

6. Nested if…else

Nested if…else statements in JavaScript allow us to create complex conditional logic by checking multiple conditions in a hierarchical manner. Each if statement can have an associated else block, and within each if or else block, you can nest another if…else statement. This nesting can continue to multiple levels, but it’s important to maintain readability and avoid excessive complexity.

Example: In this example, the outer if statement checks the weather variable. If it’s “sunny,” it further checks the temperature variable to determine the type of day it is (hot, warm, or cool). Depending on the values of weather and temperature, different messages will be logged to the console.

Please Login to comment...

Similar reads.

  • Web Technologies
  • javascript-basics
  • 105 Funny Things to Do to Make Someone Laugh
  • Best PS5 SSDs in 2024: Top Picks for Expanding Your Storage
  • Best Nintendo Switch Controllers in 2024
  • Xbox Game Pass Ultimate: Features, Benefits, and Pricing in 2024
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Home » JavaScript Tutorial » JavaScript Ternary Operator

JavaScript Ternary Operator

javascript ternary operator

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

Introduction to JavaScript ternary operator

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

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

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

Here’s the syntax of the ternary operator:

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

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

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

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

JavaScript ternary operator examples

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

1) Using the JavaScript ternary operator to perform multiple statements

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

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

2) Simplifying ternary operator example

See the following example:

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

3) Using multiple JavaScript ternary operators example

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

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

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

Dianne Pena

Quick Tip: How to Use the Ternary Operator in JavaScript

Share this article

Quick Tip: How to Use the Ternary Operator in JavaScript

Using the Ternary Operator for Value Assignment

Using the ternary operator for executing expressions, using the ternary operator for null checks, nested conditions, codepen example, faqs on how to use the ternary operator in javascript.

In this tutorial, we’ll explore the syntax of the ternary operator in JavaScript and some of its common uses.

The ternary operator (also known as the conditional operator ) can be used to perform inline condition checking instead of using if...else statements. It makes the code shorter and more readable. It can be used to assign a value to a variable based on a condition, or execute an expression based on a condition.

The ternary operator accepts three operands; it’s the only operator in JavaScript to do that. You supply a condition to test, followed by a questions mark, followed by two expressions separated by a colon. If the condition is considered to be true ( truthy ), the first expression is executed; if it’s considered to be false, the final expression is executed.

It’s used in the following format:

Here, condition is the condition to test. If its value is considered to be true , expr1 is executed. Otherwise, if its value is considered to be false , expr2 is executed.

expr1 and expr2 are any kind of expression. They can be variables, function calls, or even other conditions.

For example:

One of the most common use cases of ternary operators is to decide which value to assign to a variable. Often, a variable’s value might depend on the value of another variable or condition.

Although this can be done using the if...else statement, it can make the code longer and less readable. For example:

In this code example, you first define the variable message . Then, you use the if...else statement to determine the value of the variable.

This can be simply done in one line using the ternary operator:

Ternary operators can be used to execute any kind of expression.

For example, if you want to decide which function to run based on the value of a variable, you can do it like this using the if...else statement:

This can be done in one line using the ternary operator:

If feedback has the value yes , then the sayThankYou function will be called and executed. Otherwise, the saySorry function will be called and executed.

In many cases, you might be handling variables that may or may not have a defined value — for example, when retrieving results from user input, or when retrieving data from a server.

Using the ternary operator, you can check that a variable is not null or undefined just by passing the variable name in the position of the condition operand.

This is especially useful when the variable is an object . If you try to access a property on an object that’s actually null or undefined , an error will occur. Checking that the object is actually set first can help you avoid errors.

In the first part of this code block, book is an object with two properties — name and author . When the ternary operator is used on book , it checks that it’s not null or undefined . If it’s not — meaning it has a value — the name property is accessed and logged into the console. Otherwise, if it’s null, No book is logged into the console instead.

Since book is not null , the name of the book is logged in the console. However, in the second part, when the same condition is applied, the condition in the ternary operator will fail, since book is null . So, “No book” will be logged in the console.

Although ternary operators are used inline, multiple conditions can be used as part of a ternary operator’s expressions. You can nest or chain more than one condition to perform condition checks similar to if...else if...else statements.

For example, a variable’s value may depend on more than one condition. It can be implemented using if...else if...else :

In this code block, you test multiple conditions on the score variable to determine the letter grading of the variable.

These same conditions can be performed using ternary operators as follows:

The first condition is evaluated, which is score < 50 . If it’s true , then the value of grade is F . If it’s false , then the second expression is evaluated which is score < 70 .

This keeps going until either all conditions are false , which means the grade’s value will be A , or until one of the conditions is evaluated to be true and its truthy value is assigned to grade .

In this live example, you can test how the ternary operator works with more multiple conditions.

If you enter a value less than 100, the message “Too Low” will be shown. If you enter a value greater than 100, the message “Too High” will be shown. If you enter 100, the message “Perfect” will be shown.

See the Pen Ternary Operator in JS by SitePoint ( @SitePoint ) on CodePen .

As explained in the examples in this tutorial, the ternary operator in JavaScript has many use cases. In many situations, the ternary operator can increase the readability of our code by replacing lengthy if...else statements.

Related reading:

  • 25+ JavaScript Shorthand Coding Techniques
  • Quick Tip: How to Use the Spread Operator in JavaScript
  • Back to Basics: JavaScript Object Syntax
  • JavaScript: Novice to Ninja

What is the Syntax of the Ternary Operator in JavaScript?

The ternary operator in JavaScript is a shorthand way of writing an if-else statement. It is called the ternary operator because it takes three operands: a condition, a result for true, and a result for false. The syntax is as follows: condition ? value_if_true : value_if_false In this syntax, the condition is an expression that evaluates to either true or false. If the condition is true, the operator returns the value_if_true . If the condition is false, it returns the value_if_false .

Can I Use Multiple Ternary Operators in a Single Statement?

Yes, you can use multiple ternary operators in a single statement. This is known as “nesting”. However, it’s important to note that using too many nested ternary operators can make your code harder to read and understand. Here’s an example of how you can nest ternary operators: let age = 15; let beverage = (age >= 21) ? "Beer" : (age < 18) ? "Juice" : "Cola"; console.log(beverage); // Output: "Juice"

Can Ternary Operators Return Functions in JavaScript?

Yes, the ternary operator can return functions in JavaScript. This can be useful when you want to execute different functions based on a condition. Here’s an example: let greeting = (time < 10) ? function() { alert("Good morning"); } : function() { alert("Good day"); }; greeting();

How Does the Ternary Operator Compare to If-Else Statements in Terms of Performance?

In terms of performance, the difference between the ternary operator and if-else statements is negligible in most cases. Both are used for conditional rendering, but the ternary operator can make your code more concise.

Can Ternary Operators be Used Without Else in JavaScript?

No, the ternary operator in JavaScript requires both a true and a false branch. If you don’t need to specify an action for the false condition, consider using an if statement instead.

How Can I Use the Ternary Operator with Arrays in JavaScript?

You can use the ternary operator with arrays in JavaScript to perform different actions based on the condition. Here’s an example: let arr = [1, 2, 3, 4, 5]; let result = arr.length > 0 ? arr[0] : 'Array is empty'; console.log(result); // Output: 1

Can Ternary Operators be Used for Multiple Conditions?

Yes, you can use ternary operators for multiple conditions. However, it can make your code harder to read if overused. Here’s an example: let age = 20; let type = (age < 13) ? "child" : (age < 20) ? "teenager" : "adult"; console.log(type); // Output: "teenager"

Can Ternary Operators be Used in Return Statements?

Yes, you can use ternary operators in return statements. This can make your code more concise. Here’s an example: function isAdult(age) { return (age >= 18) ? true : false; } console.log(isAdult(20)); // Output: true

Can Ternary Operators be Used with Strings in JavaScript?

Yes, you can use ternary operators with strings in JavaScript. Here’s an example: let name = "John"; let greeting = (name == "John") ? "Hello, John!" : "Hello, Stranger!"; console.log(greeting); // Output: "Hello, John!"

Can Ternary Operators be Used with Objects in JavaScript?

Yes, you can use ternary operators with objects in JavaScript. Here’s an example: let user = { name: "John", age: 20 }; let greeting = (user.age >= 18) ? "Hello, Adult!" : "Hello, Kid!"; console.log(greeting); // Output: "Hello, Adult!"

Dianne is SitePoint's newsletter editor. She especiallly loves learning about JavaScript, CSS and frontend technologies.

SitePoint Premium

Popular Tutorials

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

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

JavaScript Operators

  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

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

JS Functions

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

Exceptions and Modules

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

JavaScript Asynchronous

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

Miscellaneous

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

JavaScript Tutorials

JavaScript if...else Statement

JavaScript Comparison and Logical Operators

JavaScript null and undefined

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

JavaScript Ternary Operator

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

  • What is a Ternary operator?

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

Its syntax is:

The ternary operator evaluates the test condition.

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

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

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

Example: JavaScript Ternary Operator

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

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

Ternary Operator Used Instead of if...else

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

You can replace this code

The output of both programs will be the same.

  • Nested ternary operators

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

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

Table of Contents

  • Ternary operator used instead if...else

Video: JavaScript Ternary Operators

Sorry about that.

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

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

JavaScript Tutorial

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Logical OR assignment (||=)

The logical OR assignment ( ||= ) operator only evaluates the right operand and assigns to the left if the left operand is falsy .

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 :

Neither would the following trigger the setter:

In fact, if x is not falsy, y is not evaluated at all.

Setting default content

If the "lyrics" element is empty, display a default value:

Here the short-circuit is especially beneficial, since the element will not be updated unnecessarily and won't cause unwanted side-effects such as additional parsing or rendering work, or loss of focus, etc.

Note: Pay attention to the value returned by the API you're checking against. If an empty string is returned (a falsy value), ||= must be used, so that "No lyrics." is displayed instead of a blank space. However, if the API returns null or undefined in case of blank content, ??= should be used instead.

Specifications

Specification

Browser compatibility

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

  • Logical OR ( || )
  • Nullish coalescing operator ( ?? )
  • Bitwise OR assignment ( |= )

Javascript Tutorial

  • Javascript Basics Tutorial
  • Javascript - Home
  • JavaScript - Overview
  • JavaScript - Features
  • JavaScript - Enabling
  • JavaScript - Placement
  • JavaScript - Syntax
  • JavaScript - Hello World
  • JavaScript - Console.log()
  • JavaScript - Comments
  • JavaScript - Variables
  • JavaScript - let Statement
  • JavaScript - Constants
  • JavaScript - Data Types
  • JavaScript - Type Conversions
  • JavaScript - Strict Mode
  • JavaScript - Reserved Keywords
  • JavaScript Operators
  • JavaScript - Operators
  • JavaScript - Arithmetic Operators
  • JavaScript - Comparison Operators
  • JavaScript - Logical Operators
  • JavaScript - Bitwise Operators
  • JavaScript - Assignment Operators

JavaScript - Conditional Operators

  • JavaScript - typeof Operator
  • JavaScript - Nullish Coalescing Operator
  • JavaScript - Delete Operator
  • JavaScript - Comma Operator
  • JavaScript - Grouping Operator
  • JavaScript - Yield Operator
  • JavaScript - Spread Operator
  • JavaScript - Exponentiation Operator
  • JavaScript - Operator Precedence
  • JavaScript Control Flow
  • JavaScript - If...Else
  • JavaScript - While Loop
  • JavaScript - For Loop
  • JavaScript - For...in
  • Javascript - For...of
  • JavaScript - Loop Control
  • JavaScript - Break Statement
  • JavaScript - Continue Statement
  • JavaScript - Switch Case
  • JavaScript - User Defined Iterators
  • JavaScript Functions
  • JavaScript - Functions
  • JavaScript - Function Expressions
  • JavaScript - Function Parameters
  • JavaScript - Default Parameters
  • JavaScript - Function() Constructor
  • JavaScript - Function Hoisting
  • JavaScript - Self-Invoking Functions
  • JavaScript - Arrow Functions
  • JavaScript - Function Invocation
  • JavaScript - Function call()
  • JavaScript - Function apply()
  • JavaScript - Function bind()
  • JavaScript - Closures
  • JavaScript - Variable Scope
  • JavaScript - Global Variables
  • JavaScript - Smart Function Parameters
  • JavaScript Objects
  • JavaScript - Number
  • JavaScript - Boolean
  • JavaScript - Strings
  • JavaScript - Arrays
  • JavaScript - Date
  • JavaScript - DataView
  • JavaScript - Handler
  • JavaScript - Math
  • JavaScript - RegExp
  • JavaScript - Symbol
  • JavaScript - Sets
  • JavaScript - WeakSet
  • JavaScript - Maps
  • JavaScript - WeakMap
  • JavaScript - Iterables
  • JavaScript - Reflect
  • JavaScript - TypedArray
  • JavaScript - Template Literals
  • JavaScript - Tagged Templates
  • Object Oriented JavaScript
  • JavaScript - Objects
  • JavaScript - Classes
  • JavaScript - Object Properties
  • JavaScript - Object Methods
  • JavaScript - Static Methods
  • JavaScript - Display Objects
  • JavaScript - Object Accessors
  • JavaScript - Object Constructors
  • JavaScript - Native Prototypes
  • JavaScript - ES5 Object Methods
  • JavaScript - Encapsulation
  • JavaScript - Inheritance
  • JavaScript - Abstraction
  • JavaScript - Polymorphism
  • JavaScript - Destructuring Assignment
  • JavaScript - Object Destructuring
  • JavaScript - Array Destructuring
  • JavaScript - Nested Destructuring
  • JavaScript - Optional Chaining
  • JavaScript - Garbage Collection
  • JavaScript - Global Object
  • JavaScript - Mixins
  • JavaScript - Proxies
  • JavaScript Versions
  • JavaScript - History
  • JavaScript - Versions
  • JavaScript - ES5
  • JavaScript - ES6
  • ECMAScript 2016
  • ECMAScript 2017
  • ECMAScript 2018
  • ECMAScript 2019
  • ECMAScript 2020
  • ECMAScript 2021
  • ECMAScript 2022
  • ECMAScript 2023
  • JavaScript Cookies
  • JavaScript - Cookies
  • JavaScript - Cookie Attributes
  • JavaScript - Deleting Cookies
  • JavaScript Browser BOM
  • JavaScript - Browser Object Model
  • JavaScript - Window Object
  • JavaScript - Document Object
  • JavaScript - Screen Object
  • JavaScript - History Object
  • JavaScript - Navigator Object
  • JavaScript - Location Object
  • JavaScript - Console Object
  • JavaScript Web APIs
  • JavaScript - Web API
  • JavaScript - History API
  • JavaScript - Storage API
  • JavaScript - Forms API
  • JavaScript - Worker API
  • JavaScript - Fetch API
  • JavaScript - Geolocation API
  • JavaScript Events
  • JavaScript - Events
  • JavaScript - DOM Events
  • JavaScript - addEventListener()
  • JavaScript - Mouse Events
  • JavaScript - Keyboard Events
  • JavaScript - Form Events
  • JavaScript - Window/Document Events
  • JavaScript - Event Delegation
  • JavaScript - Event Bubbling
  • JavaScript - Event Capturing
  • JavaScript - Custom Events
  • JavaScript Error Handling
  • JavaScript - Error Handling
  • JavaScript - try...catch
  • JavaScript - Debugging
  • JavaScript - Custom Errors
  • JavaScript - Extending Errors
  • JavaScript Important Keywords
  • JavaScript - this Keyword
  • JavaScript - void Keyword
  • JavaScript - new Keyword
  • JavaScript - var Keyword
  • JavaScript HTML DOM
  • JavaScript - HTML DOM
  • JavaScript - DOM Methods
  • JavaScript - DOM Document
  • JavaScript - DOM Elements
  • JavaScript - DOM Forms
  • JavaScript - Changing HTML
  • JavaScript - Changing CSS
  • JavaScript - DOM Animation
  • JavaScript - DOM Navigation
  • JavaScript - DOM Collections
  • JavaScript - DOM Node Lists
  • JavaScript Miscellaneous
  • JavaScript - Ajax
  • JavaScript - Generators
  • JavaScript - Async Iteration
  • JavaScript - Atomics Objects
  • JavaScript - Rest Parameter
  • JavaScript - Page Redirect
  • JavaScript - Dialog Boxes
  • JavaScript - Page Printing
  • JavaScript - Validations
  • JavaScript - Animation
  • JavaScript - Multimedia
  • JavaScript - Image Map
  • JavaScript - Browsers
  • JavaScript - JSON
  • JavaScript - Multiline Strings
  • JavaScript - Date Formats
  • JavaScript - Get Date Methods
  • JavaScript - Set Date Methods
  • JavaScript - Random Number
  • JavaScript - Modules
  • JavaScript - Dynamic Imports
  • JavaScript - Export and Import
  • JavaScript - BigInt
  • JavaScript - Blob
  • JavaScript - Unicode
  • JavaScript - Execution Context
  • JavaScript - Shallow Copy
  • JavaScript - Call Stack
  • JavaScript - Design Patterns
  • JavaScript - Reference Type
  • JavaScript - LocalStorage
  • JavaScript - SessionStorage
  • JavaScript - IndexedDB
  • JavaScript - Clickjacking Attack
  • JavaScript - Currying
  • JavaScript - Graphics
  • JavaScript - Canvas
  • JavaScript - Debouncing
  • JavaScript - Common Mistakes
  • JavaScript - Performance
  • JavaScript - Best Practices
  • JavaScript - Style Guide
  • JavaScript - Ninja Code
  • JavaScript Useful Resources
  • JavaScript - Questions And Answers
  • JavaScript - Quick Guide
  • JavaScript - Resources
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

JavaScript Conditional Operators

The conditional operator in JavaScript first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. The conditional operator is also known as the ternary operator.

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

There are six falsy values in JavaScript. These are − 0 (zero), false, empty string ('' or ""), null, undefined, and NaN. All other values are treated as truthy in JavaScript.

Following is the syntax of conditional (ternary) operator in JavaScript −

Here, we have explained the parameters in the above statement.

  • condition − It is a conditional statement.

If the value of the condition is any falsy value, the result of the expression will be the value of exp2 ; otherwise, it will be the value of exp1 .

It will produce the following result −

In the example below, we assign the value to the object property according to the conditional statement’s result.

Now, imagine what if you need to write the if-else statement to assign value to each property conditionally. The code will become complex, but with the ternary operator, you can easily do it with a single line of code.

This example demonstrates that you can also use the expression instead of values. According to the conditional statement, control flow evaluates the first or second expression and assigns the resultant value to the 'result' variable.

In short, you can use the ternary or conditional operator to shorten the code, which uses the if-else statement.

Handling null values

We can use the JavaScript conational operator to handle null value to set a default value if the user passes a null value.

Try the following example −

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Assign variable in if condition statement, good practice or not? [closed]

I moved one years ago from classic OO languages such like Java to JavaScript. The following code is definitely not recommended (or even not correct) in Java:

Basically I just found out that I can assign a variable to a value in an if condition statement, and immediately check the assigned value as if it is boolean.

For a safer bet, I usually separate that into two lines of code, assign first then check the variable, but now that I found this, I am just wondering whether is it good practice or not in the eyes of experienced JavaScript developers?

Carson's user avatar

  • "The following code is definitely not recommended (or event not correct) in Java..." Is it even correct in JavaScript? Because, as far as I can see, you return an integer ( return parseInt(...) ) if dayNumber != -1 is true, but a boolean if it is false. –  Daniel Kvist Commented Jul 3, 2015 at 10:35

10 Answers 10

I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or === . For example, when you see this:

you don't know if that's what they meant to do, or if they intended to write this:

If you really want to do the assignment in place, I would recommend doing an explicit comparison as well:

Matthew Crumley's user avatar

  • 2 @Matthew Crumley : this answers my question in a clear way. I am not checking by assigning but checking whatever the value evaluates to be after the assignment. Is this understanding right? –  Michael Mao Commented Apr 5, 2010 at 2:10
  • 2 @Michael: yes, that's correct. Adding the comparison basically just makes your intentions more clear. –  Matthew Crumley Commented Apr 5, 2010 at 2:13
  • 5 The last example doesn't work, however, if you're testing for fail/success of a function that returns a boolean. In other words, while if (resultArr = myNeedle.exec(myHaystack)) {...} works, if ((resultArr = myNeedle.exec(myHaystack)) === true) {...} does not because the assignment to resultArr is always truthy even when the function result is not. If anyone uses this.. construct, remember to declare the result variable first; 'var' is not legal within the if condition statement. –  Ville Commented Apr 15, 2013 at 22:10
  • 4 You can use if (!!(value = someFunction())) , but as you said, the problem is that you can't use var inside if so you either end up creating a global, or achieve nothing as you have to declare value in a separate line anyway. Shame, I really liked this construction in C++. –  riv Commented Mar 30, 2015 at 17:05
  • 1 @riv, you're right; in case the function returns a boolean – like I said in my above comment – then the conditional works as expected. But if the function returns a boolean (as in my example) then the whole construct is kind of non-sensical; clearly my line of thinking was – judging from the example – that the function would return an array. A quick test indicates that the condition evaluates to true only when the function returns true , but in all other cases (including when an array, string, number, or null is returned) it evaluates to false . –  Ville Commented Sep 10, 2015 at 4:06

I see no proof that it is not good practice. Yes, it may look like a mistake but that is easily remedied by judicious commenting. Take for instance:

Why should that function be allowed to run a 2nd time with:

Because the first version LOOKS bad? I cannot agree with that logic.

borisdiakur's user avatar

  • 58 Not to dig up an old comment, but I don't agree with your arguments. Readable code should explain itself without the need for a comment - adding a comment to confusing code isn't a remedy. As for the second part, which says the alternative is to call the function again, I don't think anyone intends to do that. Instead you would do x = processorItensiveFunction(); if(x) { alert(x); } –  maksim Commented Dec 25, 2014 at 23:34
  • 13 @maksim: I like readable code, but that doesn't necessarily mean code should be dumbed down or too verbose. Spreading things over multiple lines and juggling values between variables can actually lead to worse code. Inserted code can have unforeseen side effects in a weakly typed / flexible language like JS. Assignment in a conditional statement is valid in javascript, because your just asking "if assignment is valid, do something which possibly includes the result of the assignment". But indeed, assigning before the conditional is also valid, not too verbose, and more commonly used. –  okdewit Commented Jul 15, 2015 at 11:30
  • 1 @maksim why would you think if ( ! x = anyFunction() ) is not readable? It doesn't need any comments whatsoever. –  jdrake Commented Jun 8, 2017 at 10:08
  • If you fix OPC, work with other devs of varying skill levels (in other words, you are a professional) you will hate that this is even possible. –  davidjmcclelland Commented Oct 17, 2017 at 19:32
  • 3 @maksim - also your solution would be very inconvenient in an if-else situation. Consider- if (condition) {...} else if (x = processorIntensiveFunction()) {alert(x)} Your prior x = processorIntensiveFunction(); would be a wasted effort should the initial condition be true. –  Adrian Bartholomew Commented Jun 3, 2019 at 1:03

I did it many times. To bypass the JavaScript warning, I add two parens:

You should avoid it, if you really want to use it, write a comment above it saying what you are doing.

Ming-Tang's user avatar

  • 2 @SHiNKiROU : how can I see javascript warnings? Is there a Javascript compiler? or the interpreter will generate some sort of warning? I am using Firefox console as in javascript debugging all the time but never see any similar outputs. Sorry about my limited experience. –  Michael Mao Commented Apr 5, 2010 at 1:57
  • 6 @Michael: JSLint ( jslint.com ) is a popular program/library that checks JavaScript programs for possible mistakes or bad code. –  Matthew Crumley Commented Apr 5, 2010 at 2:44
  • Use Mozilla Firefox with Firebug and/or Web Developer extension to check warnings. –  Ming-Tang Commented Apr 5, 2010 at 3:33
  • 1 I just tried it with if ((a = [1, 2]).length > 0) { console.log(a); } where a isn't initialized anywhere yet and it indeed worked (nice! makes using regex much easier). Is this correct that I don't need any of var|const|let here? Do you happen to know where I could read more about this trick ? –  t3chb0t Commented Oct 27, 2019 at 11:16
  • 3 @t3chb0t: As of 2022, in JavaScript, the = assignment without var|let|const is an expression . That means, it can be used anywhere expressions can be used, including within an if(...) . Also note, that unless the variable a has been declared earlier, it will be global . This is usually not what you want. –  Michael Commented Sep 5, 2022 at 14:04

There is one case when you do it, with while -loops. When reading files, you usualy do like this:

Look at the while -loop at line 9. There, a new line is read and stored in a variable, and then the content of the loop is ran. I know this isn't an if -statement, but I guess a while loop can be included in your question as well.

The reason to this is that when using a FileInputStream , every time you call FileInputStream.readLine() , it reads the next line in the file, so if you would have called it from the loop with just fileIn.readLine() != null without assigning the variable, instead of calling (currentLine = fileIn.readLine()) != null , and then called it from inside of the loop too, you would only get every second line.

Hope you understand, and good luck!

user229044's user avatar

If you were to refer to Martin Fowlers book Refactoring improving the design of existing code ! Then there are several cases where it would be good practice eg. long complex conditionals to use a function or method call to assert your case:

"Motivation One of the most common areas of complexity in a program lies in complex conditional logic. As you write code to test conditions and to do various things depending on various conditions, you quickly end up with a pretty long method. Length of a method is in itself a factor that makes it harder to read, but conditions increase the difficulty. The problem usually lies in the fact that the code, both in the condition checks and in the actions, tells you what happens but can easily obscure why it happens. As with any large block of code, you can make your intention clearer by decomposing it and replacing chunks of code with a method call named after the intention of that block of code. > With conditions you can receive further benefit by doing this for the conditional part and each of the alternatives. This way you highlight the condition and make it clearly what you > are branching on. You also highlight the reason for the branching."

And yes his answer is also valid for Java implementations. It does not assign the conditional function to a variable though in the examples.

Community's user avatar

  • This seems to be about using functions/methods, especially when also using conditionals. This does not address the question. –  Akaisteph7 Commented May 11, 2023 at 15:41

I came here from golang, where it's common to see something like

In which err is scoped to that if block only. As such, here's what I'm doing in es6, which seems pretty ugly, but doesn't make my rather strict eslint rules whinge, and achieves the same.

The extra braces define a new, uh, "lexical scope"? Which means I can use const , and err isn't available to the outer block.

Adam Barnes's user avatar

You can do this in Java too. And no, it's not a good practice. :)

(And use the === in Javascript for typed equality. Read Crockford's The Good Parts book on JS.)

Ben Zotto's user avatar

  • 1 @quixoto : Could I do this trick in Java? I wonder... I don't have jdk by hand atm so I am unable to get a sample code in Java. From my poor memory, Java will just get you a Runtime error if the returning value evaluates something not boolean as in if conditional statement, right? –  Michael Mao Commented Apr 5, 2010 at 1:52
  • 2 Ah, yes, in Java it's type-checked to be a boolean type. But you can do if (foo = getSomeBoolValue()) { } –  Ben Zotto Commented Apr 5, 2010 at 1:57
  • 1 yeah that's right. a boolean variable to test whether something succeeded and another variable to store the value returned. That's how Java does its job, I am too familiar with that so I feel strange to see Javascript can do two things in one mere line :) –  Michael Mao Commented Apr 5, 2010 at 2:00
  • @BenZotto it's not good practice why? "To avoid accidental misuse of a variable, it is usually a good idea to introduce the variable into the smallest scope possible. In particular, it is usually best to delay the definition of a variable until one can give it an initial value ... One of the most elegant applications of these two principles is to declare a variable in a conditional." -- Stroustrup, "The C++ Programming Language." –  jdrake Commented Jun 8, 2017 at 10:12
  • 2 Hi, I came here as node.js javascript user. Why there it's not good practice in one case I had pain with: if (myvar = 'just a test') Creates a node.js GLOBAL variable myvar ( nodejs.org/docs/latest-v12.x/api/globals.html#globals_global ). So if you're like me and used that variable in server request handling (coming back to it after a few seconds when other requests might have dropped in and stuff), you can be surprised at what results you get. So the recommendation is: Be aware that this pattern creates a global variable in node.js. –  tinkering.online Commented May 2, 2020 at 12:01

You can do assignments within if statements in Java as well. A good example would be reading something in and writing it out:

http://www.exampledepot.com/egs/java.io/CopyFile.html?l=new

Nitrodist's user avatar

  • @Nitrodist : thanks for this example. I am really not pro in either Java or javascript... It is good to know this approach is also feasible in Java :) –  Michael Mao Commented Apr 5, 2010 at 10:46
  • 1 I don't see the point of this. You can do it in Java, PHP and many other languages. The question was about Javascript. –  pmrotule Commented Nov 24, 2016 at 10:55
  • No it isn't necessarily, you need to re-read the question carefully. –  Nitrodist Commented Dec 1, 2016 at 21:14

It's not good practice. You soon will get confused about it. It looks similiar to a common error: misuse "=" and "==" operators.

You should break it into 2 lines of codes. It not only helps to make the code clearer, but also easy to refactor in the future. Imagine that you change the IF condition? You may accidently remove the line and your variable no longer get the value assigned to it.

thethanghn's user avatar

  • @thethanghn: that exactly what I am afraid of. when I get older and lazy I just don't want to type more into the code if fewer keystrokes will just suffice :) –  Michael Mao Commented Apr 5, 2010 at 2:37
  • 2 No, I don't get confused and I do it all the time. There are benefits to it. –  jdrake Commented Jun 8, 2017 at 10:12
  • It really depends, though, doesn't it? If you come from a 'C' background (and other languages based on C), then the construct is very familiar, and the alternatives are very awkward. IMO, it is something that is learned once and then you know. It's not something you will trip over more than once. –  Max Waterman Commented Jun 10, 2020 at 1:33

you could do something like so:

Joseph Le Brech's user avatar

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

  • The Overflow Blog
  • One of the best ways to get value for AI coding tools: generating tests
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • How to prevent a bash script from running repeatedly at the start of the terminal
  • Movie where a young director's student film gets made (badly) by a major studio
  • Whom did Jesus' followers accompany -- a soldier or a layman?
  • What factors cause differences between dried herb/spice brands?
  • Is there an essential distinction between experienced and observed consciousness?
  • Why was Esther included in the canon?
  • How did NASA figure out when and where the Apollo capsule would touch down on the ocean?
  • What would be an appropriate translation of Solitude?
  • Doesn't nonlocality follow from nonrealism in the EPR thought experiment and Bell tests?
  • Understanding symmetry in a double integral
  • What is the oldest open math problem outside of number theory?
  • What makes amplifiers so expensive?
  • How can I switch from MAG to TRU heading in a 737?
  • Fast leap year check
  • How to reply to a revise and resubmit review, saying is all good?
  • Function with memories of its past life
  • Why is the \[ThickSpace] character defined as 5/18 em instead of 1/4 em as in Unicode?
  • Longtable goes beyond the right margin and footnote does not fit under the table
  • Keyboard shortcuts for running last command with changes?
  • C++ std::function-like queue
  • Drill perpendicular hole through thick lumber using handheld drill
  • Is it really a "space walk" (EVA proper) if you don't get your feet wet (in space)?
  • Will "universal" SMPS work at any voltage in the range, even DC?
  • Are there something like standard documents for 8.3 filename which explicitly mention about the folder names?

js conditional assignment

JavaScript If-Else and If-Then – JS Conditional Statements

Jessica Wilkins

There will be times where you will want to write commands that handle different decisions in your code.

For example, if you are coding a bot, you can have it respond with different messages based on a set of commands it receives.

In this article, I will explain what an if...else statement is and provide code examples. We will also look at the conditional (ternary) operator which you can use as a shorthand for the if...else statement.

What is an if...else statement in JavaScript?

The if...else is a type of conditional statement that will execute a block of code when the condition in the if statement is truthy . If the condition is falsy , then the else block will be executed.

Truthy and falsy values are converted to true or false in if statements.

Any value that is not defined as falsy would be considered truthy in JavaScript.

Here is a list of falsy values:

  • -0 (negative zero)
  • 0n (BigInt zero)
  • "" , '' , ```` (empty string)
  • NaN (not a number)

Examples of if...else statements in JavaScript

In this example, the condition for the if statement is true so the message printed to the console would be "Nick is an adult."

Image

But if I change the age variable to be less than 18, then the condition would be false and the code would execute the else block instead.

Image

Examples of multiple conditions (if...else if...else statements) in JavaScript

There will be times where you want to test multiple conditions. That is where the else if block comes in.

When the if statement is false , the computer will move onto the else if statement. If that is also false , then it will move onto the else block.

In this example, the else if block would be executed because Alice is between the ages of 18 and 21.

Image

When to use switch statements over if...else statements?

There are times in JavaScript where you might consider using a switch statement instead of an if else statement.

switch statements can have a cleaner syntax over complicated if else statements.

Take a look at the example below – instead of using this long if else statement, you might choose to go with an easier to read switch statement.

switch statements will not be appropriate to use in all situations. But if you feel like the if else statements are long and complicated, then a switch statement could be an alternative option.

The logical AND (&&) operator and if...else statements in JavaScript

In the logical AND ( && ) operator, if both conditions are true , then the if block will be executed. If one or both of the conditions are false , then the else block will be executed.

In this example, since age is greater than 16 and the ownsCar variable is true , the if block will run. The message printed to the console will be "Jerry is old enough to drive and has his own car."

Image

If I change the age variable to be less than 16, then both conditions are no longer true and the else block would be executed instead.

Image

The logical OR (||) operator and if...else statements in JavaScript

In the logical OR ( || ) operator, if one or both of the conditions are true , then the code inside the if statement will execute.

In this example, even though the isSale variable is set to false , the code inside the if block will still execute because the boyfriendIsPaying variable is set to true .

Image

If I were to change the value of the boyfriendIsPaying variable to false , then the else block would execute because both conditions are false .

Image

The logical NOT (!) operator and if...else statements in JavaScript

The logical NOT ( ! ) operator will take something that is true and make it false . It will also take something that is false and make it true .

We can modify the example from earlier to use the ! operator to make the boyfriendIsPaying variable false . Since both conditions are false , the else block would be executed.

Image

Conditional (ternary) operator in JavaScript

If you have a short if else statement, then you might choose to go with the ternary operator. The word ternary means something composed of three parts.

This is the basic syntax for a ternary operator:

The condition goes before the ? mark and if it is true , then the code between the ? mark and : would execute. If the condition is false , then the code after the : would execute.

In this example, since age is greater than 18, then the message to the console would be "Can vote".

Image

This is what the code would look like using an if else statement:

if else statements will execute a block of code when the condition in the if statement is truthy . If the condition is falsy , then the else block will be executed.

There will be times where you want to test multiple conditions and you can use an if...else if...else statement.

If you feel like the if else statement is long and complicated, then a switch statement could be an alternative option.

Using logical operators to test multiple conditions can replace nested if else statements.

The ternary operator can be used to write shorter code for a simple if else statement.

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Switch Case vs. If-Else in JavaScript Explained

Switch case and if-else offer two different approaches to writing conditional statements in JavaScript. Here’s how to determine which one to use.

Michelle Wong

In JavaScript , the switch case and if-else statement provide two different ways to write a conditional statement .  The switch case is used to test the value of the given variable against a list of case values to determine which code block to run. The if-else statement nests conditions under if and else statements that determine which code to execute. It can be difficult to determine which one to use.

Switch Case vs. If-Else Statements in JavaScript Explained

  • Switch case: Switch case allows conditions to be separated into different case blocks. The expression inside the switch statement decides what to execute. 
  •   If-else statements: If-else statements nest conditions under if and else statements. The condition in the if statement determines whether to execute code under the if block or the else block.  

However, a switch statement is usually more efficient than a set of nested ifs. When you have to choose which one to use, it’s best to decide based on readability and the expression that the statement is testing.

Differences Between Switch Case vs. If-Else 

  • The expression inside of an if statement decides whether to execute the statements inside the if block or the else block. For switch, the expression inside the switch statement decides which case to execute.
  • The if-else statement checks for equality as well as for logical expression. On the other hand, switch checks only for equality.
  • The if statement evaluates integer, character, pointer or floating-point type or boolean type. The switch statement evaluates only character or an integer datatype.
  • In if-else statements, the if statement determines whether the statement under the if block will execute or the statement under else block statement will execute. However, the expression in the switch statement decides which case to execute, however, if you don’t apply a break statement after each case , it will execute until the end of switch statement.
  • For an if-else statement, if the expression inside of the if turns out to be false, the statement inside of the else block will be executed. For the switch statement, if the expression inside of the switch statement turns out to be false, then the default statements are executed.
  • It can be difficult to edit if-else statements since it’s tedious to trace where the correction is required. Many people agree that it’s much simpler to edit switch statements since they’re easy to trace.

More on Software Engineering JavaScript Check If a Checkbox Is Checked

Switch Case vs. If-Else Syntax

This is the general syntax of an if-else statement:

And this is the general syntax for switch:

The if-else ladder is of type strict condition check, while switch is of type jump value catching.

More on Software Engineering Guide to the JavaScript Array Filter() Method

Advantages of Switch Case vs. If-Else 

  • A switch statement works much faster than the equivalent if-else ladder because the compiler generates a jump table for a switch during compilation. During execution, instead of checking which case is satisfied, it only decides which case has to be executed.
  • A switch case statement is more readable compared to if-else statements.

In the end, the choice is yours and I hope this blog helps lead you in the right path to making the most informed decision when to use an if-else statement verses a switch case!

Frequently Asked Questions

Is switch better than if-else in javascript .

Switch case is considered faster and more readable than nested if-else statements. If-else statements require the compiler to check each statement to determine if a condition is met. Switch case is more efficient because it allows the compiler to determine only which case has to be executed. 

What is the key difference between switch case vs. if-else statements in JavaScript?

  • If-else statements involving branching conditions under if and else statements. The code executes the if statement if a given condition is met, otherwise it executes the else statement. Here’s how the syntax looks:
  • In switch case , the expression in the switch statement decides which case to execute along with a break statement after each case. This allows the compiler to execute only the code in which the case condition is met, making it a more streamlined version of if-else. The syntax looks like this:

Recent Software Engineering Perspectives Articles

Why Separating Knowledge, Compute and Storage is the Next Big Leap in Data Platforms

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 assignment, javascript assignment operators.

Assignment operators assign values to JavaScript variables.

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

Shift Assignment Operators

Operator Example Same As
<<= x <<= y x = x << y
>>= x >>= y x = x >> y
>>>= x >>>= y x = x >>> y

Bitwise Assignment Operators

Operator Example Same As
&= x &= y x = x & y
^= x ^= y x = x ^ y
|= x |= y x = x | y

Logical Assignment Operators

Operator Example Same As
&&= x &&= y x = x && (x = y)
||= x ||= y x = x || (x = y)
??= x ??= y x = x ?? (x = y)

The = Operator

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

The += operator.

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

The -= operator.

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

The *= operator.

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

The **= operator.

The Exponentiation Assignment Operator raises a variable to the power of the operand.

Exponentiation Assignment Example

The /= operator.

The Division Assignment Operator divides a variable.

Division Assignment Example

The %= operator.

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

Advertisement

The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

The >>= operator.

The Right Shift Assignment Operator right shifts a variable (signed).

Right Shift Assignment Example

The >>>= operator.

The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).

Unsigned Right Shift Assignment Example

The &= operator.

The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.

Bitwise AND Assignment Example

The |= operator.

The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns the result to the variable.

Bitwise OR Assignment Example

The ^= operator.

The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and assigns the result to the variable.

Bitwise XOR Assignment Example

The &&= operator.

The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned.

Logical AND Assignment Example

The &&= operator is an ES2020 feature .

The ||= Operator

The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

Logical OR Assignment Example

The ||= operator is an ES2020 feature .

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.

Nullish Coalescing Assignment Example

The ??= operator is an ES2020 feature .

Test Yourself With Exercises

Use the correct assignment operator that will result in x being 15 (same as x = x + y ).

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. Top 40 Javascript One Liners

    js conditional assignment

  2. JavaScript Conditional Statements

    js conditional assignment

  3. Basic Javascript Tutorial

    js conditional assignment

  4. Conditional Statements in JavaScript

    js conditional assignment

  5. JavaScript Conditional Statements Tutorial

    js conditional assignment

  6. JavaScript Conditional Statements

    js conditional assignment

VIDEO

  1. Java Script Logical Operator Lesson # 08

  2. React JS Conditional Rendering

  3. Javascript

  4. js conditional and function

  5. Conditional and selected signal assignment statements

  6. Next JS tutorial in Hindi #11 Conditional Layout in next.js 13

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

  3. How do you use the ? : (conditional) operator in JavaScript?

    It's a little hard to google when all you have are symbols ;) The terms to use are "JavaScript conditional operator". ... the whole point of the conditional ternary is to shorten conditional assignment values otherwise you should just use an if statement - TheRealMrCrowley. Commented May 5, 2017 at 18:05.

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

  5. JavaScript Operators Reference

    JavaScript Operators. Operators are used to assign values, compare values, perform arithmetic operations, and more. There are different types of JavaScript operators: Arithmetic Operators. Assignment Operators. Comparison Operators. Logical Operators. Conditional Operators. Type Operators.

  6. JavaScript Conditionals: The Basics with Examples

    Conditional statements control behavior in JavaScript and determine whether or not pieces of code can run. There are multiple different types of conditionals in JavaScript including: "If" statements: where if a condition is true it is used to specify execution for a block of code.

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

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

  9. How to Use the Ternary Operator in JavaScript

    Inside the function, we use the ternary operator to check if the number is even or odd. If the number modulo 2 equals 0 (meaning it's divisible by 2 with no remainder), then the condition evaluates to true, and the string "even" is assigned to the result variable. If the condition evaluates to false (meaning the number is odd), the string "odd ...

  10. How to Use the Ternary Operator in JavaScript

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

  11. Conditional Statements in JavaScript

    There are several methods that can be used to perform Conditional Statements in JavaScript. Executes a block of code if a specified condition is true. Executes a block of code if the same condition of the preceding if statement is false. Adds more conditions to the if statement, allowing for multiple alternative conditions to be tested.

  12. JavaScript Ternary Operator

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

  13. Make Your Code Cleaner with JavaScript Ternary Operator

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

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

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

  15. A definitive guide to conditional logic in JavaScript

    Using isEven and JavaScript's built-in universal function, we can run [2, 4, 6, 8].every(isEven) and find that this is true. _Array.prototype.every_ is JavaScript's Universal Statement. Existential Statements. An existential statement makes a specific claim about a set: at least one element in the set returns true for the predicate function ...

  16. JavaScript Ternary Operator (with Examples)

    Output 1. Enter your marks: 78 You pass the exam. Suppose the user enters 78.Then the condition marks >= 40 is checked which evaluates to true.So the first expression pass is assigned to the result variable.. Output 2. Enter your marks: 35 You fail the exam.

  17. Logical OR assignment (||=)

    The logical OR assignment (||=) operator only evaluates the right operand and assigns to the left if the left operand is falsy. 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 ...

  18. JavaScript

    JavaScript Conditional Operators. The conditional operator in JavaScript first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. The conditional operator is also known as the ternary operator.. The JavaScript conditional (ternary) operator is only operator that takes three operands - a condition ...

  19. javascript

    Assignment in a conditional statement is valid in javascript, because your just asking "if assignment is valid, do something which possibly includes the result of the assignment". But indeed, assigning before the conditional is also valid, not too verbose, and more commonly used. - okdewit.

  20. JavaScript If-Else and If-Then

    What is an if...else statement in JavaScript? The if...else is a type of conditional statement that will execute a block of code when the condition in the if statement is truthy. If the condition is falsy, then the else block will be executed. Truthy and falsy values are converted to true or false in if statements.

  21. Switch Case vs. If-Else in JavaScript Explained

    A tutorial on when to use switch case vs. if-else in JavaScript. | Video: Ijemma Onwuzulike. More on Software Engineering Guide to the JavaScript Array Filter() Method . Advantages of Switch Case vs. If-Else . A switch statement works much faster than the equivalent if-else ladder because the compiler generates a jump table for a switch during ...

  22. JavaScript Assignment

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.