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

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: This example demonstrates how nested if…else statements can be used to handle different scenarios based on multiple conditions.

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

  • javascript-basics
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Screen-Shot-2021-08-09-at-3.18.12-AM

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.

Screen-Shot-2021-08-09-at-3.17.07-AM

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.

Screen-Shot-2021-08-09-at-3.33.33-AM

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

Screen-Shot-2021-08-09-at-4.22.49-AM

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.

Screen-Shot-2021-08-09-at-4.20.19-AM

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 .

Screen-Shot-2021-08-09-at-4.40.36-AM

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

Screen-Shot-2021-08-09-at-4.42.12-AM

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.

Screen-Shot-2021-08-09-at-5.02.04-AM

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

Screen-Shot-2021-08-09-at-5.25.14-AM

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.

I am a musician and a programmer.

If you read this far, thank the author to show them you care. Say Thanks

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

  • Skip to main content
  • Select language
  • Skip to search
  • Expressions and operators
  • Operator precedence

Left-hand-side expressions

« Previous Next »

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

A complete and detailed list of operators and expressions is also available in the reference .

JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence.

  • Assignment operators
  • Comparison operators
  • Arithmetic operators
  • Bitwise operators

Logical operators

String operators, conditional (ternary) operator.

  • Comma operator

Unary operators

  • Relational operator

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

For example, 3+4 or x*y .

A unary operator requires a single operand, either before or after the operator:

For example, x++ or ++x .

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple 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 .

There are also compound assignment operators that are shorthand for the operations listed in the following table:

Compound assignment operators
Name Shorthand operator Meaning

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:

Comparison operators
Operator Description Examples returning true
( ) Returns if the operands are equal.

( ) Returns if the operands are not equal.
( ) Returns if the operands are equal and of the same type. See also and .
( ) Returns if the operands are of the same type but not equal, or are of different type.
( ) Returns if the left operand is greater than the right operand.
( ) Returns if the left operand is greater than or equal to the right operand.
( ) Returns if the left operand is less than the right operand.
( ) Returns if the left operand is less than or equal to the right operand.

Note:  ( => ) is not an operator, but the notation for Arrow functions .

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:

In addition to the standard arithmetic operations (+, -, * /), JavaScript provides the arithmetic operators listed in the following table:

Arithmetic operators
Operator Description Example
( ) Binary operator. Returns the integer remainder of dividing the two operands. 12 % 5 returns 2.
( ) Unary operator. Adds one to its operand. If used as a prefix operator ( ), returns the value of its operand after adding one; if used as a postfix operator ( ), returns the value of its operand before adding one. If is 3, then sets to 4 and returns 4, whereas returns 3 and, only then, sets to 4.
( ) Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. If is 3, then sets to 2 and returns 2, whereas returns 3 and, only then, sets to 2.
( ) Unary operator. Returns the negation of its operand. If is 3, then returns -3.
( ) Unary operator. Attempts to convert the operand to a number, if it is not already. returns .
returns
( ) Calculates the to the  power, that is, returns .
returns .

A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

Bitwise operators
Operator Usage Description
Returns a one in each bit position for which the corresponding bits of both operands are ones.
Returns a zero in each bit position for which the corresponding bits of both operands are zeros.
Returns a zero in each bit position for which the corresponding bits are the same.
[Returns a one in each bit position for which the corresponding bits are different.]
Inverts the bits of its operand.
Shifts in binary representation bits to the left, shifting in zeros from the right.
Shifts in binary representation bits to the right, discarding bits shifted off.
Shifts in binary representation bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32 bit integer: Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

Bitwise operator examples
Expression Result Binary Description

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation).

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.

The shift operators are listed in the following table.

Bitwise shift operators
Operator Description Example

( )
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, yields -3, because the sign is preserved.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

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

Logical operators
Operator Usage Description
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if both operands are true; otherwise, returns .
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if either operand is true; if both are false, returns .
( ) Returns if its single operand can be converted to ; otherwise, returns .

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator.

The following code shows examples of the || (logical OR) operator.

The following code shows examples of the ! (logical NOT) operator.

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

The shorthand assignment operator += can also be used to concatenate strings.

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .

The comma operator ( , ) simply evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:

A unary operation is an operation with only one operand.

The delete operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:

where objectName is the name of an object, property is an existing property, and index is an integer representing the location of an element in an array.

The fourth form is legal only within a with statement, to delete a property from an object.

You can use the delete operator to delete variables declared implicitly but not those declared with the var statement.

If the delete operator succeeds, it sets the property or element to undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

Deleting array elements

When you delete an array element, the array length is not affected. For example, if you delete a[3] , a[4] is still a[4] and a[3] is undefined.

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete . However, trees[3] is still addressable and returns undefined .

If you want an array element to exist but have an undefined value, use the undefined keyword instead of the delete operator. In the following example, trees[3] is assigned the value undefined , but the array element still exists:

The typeof operator is used in either of the following ways:

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

For the keywords true and null , the typeof operator returns the following results:

For a number or string, the typeof operator returns the following results:

For property values, the typeof operator returns the type of value the property contains:

For methods and functions, the typeof operator returns results as follows:

For predefined objects, the typeof operator returns results as follows:

The void operator is used in either of the following ways:

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined , which has no effect in JavaScript.

The following code creates a hypertext link that submits a form when the user clicks it.

Relational operators

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

The in operator returns true if the specified property is in the specified object. The syntax is:

where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.

The following examples show some uses of the in operator.

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

The following table describes the precedence of operators, from highest to lowest.

Operator precedence
Operator type Individual operators
member
call / create instance
negation/increment
multiply/divide
addition/subtraction
bitwise shift
relational
equality
bitwise-and
bitwise-xor
bitwise-or
logical-and
logical-or
conditional
assignment
comma

A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference .

  • Expressions

An expression is any valid unit of code that resolves to a value.

Every syntactically valid expression resolves to some value but conceptually, there are two types of expressions: with side effects (for example: those that assign value to a variable) and those that in some sense evaluates and therefore resolves to value.

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to seven.

The code 3 + 4 is an example of the second expression type. This expression uses the + operator to add three and four together without assigning the result, seven, to a variable. JavaScript has the following expression categories:

  • Arithmetic: evaluates to a number, for example 3.14159. (Generally uses arithmetic operators .)
  • String: evaluates to a character string, for example, "Fred" or "234". (Generally uses string operators .)
  • Logical: evaluates to true or false. (Often involves logical operators .)
  • Primary expressions: Basic keywords and general expressions in JavaScript.
  • Left-hand-side expressions: Left values are the destination of an assignment.

Primary expressions

Basic keywords and general expressions in JavaScript.

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

Suppose a function called validate validates an object's value property, given the object and the high and low values:

You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

  • Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

Comprehensions

Comprehensions are an experimental JavaScript feature, targeted to be included in a future ECMAScript version. There are two versions of comprehensions:

Comprehensions exist in many programming languages and allow you to quickly assemble a new array based on an existing one, for example.

Left values are the destination of an assignment.

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Example: Today if you have an array and want to create a new array with the existing one being part of it, the array literal syntax is no longer sufficient and you have to fall back to imperative code, using a combination of push , splice , concat , etc. With spread syntax this becomes much more succinct:

Similarly, the spread operator works with function calls:

Document Tags and Contributors

  • l10n:priority
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • 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
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • 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: can't access lexical declaration`X' before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

This forum is now read-only. Please use our new forums! Go to forums

assignment in conditional expression javascript

What does "assignment in conditional expression" mean?

This is my code from lines 10 to 20; on lines 11, 13, and 14 it says “assignment in conditional expression” When I try the code is says “Oops, try again! Your code returned ‘The result is a tie!’ instead of ‘paper wins’ when the inputs are rock and paper”

10 var compare = function (choice1, choice2){ 11 if (choice1 = choice2) { 12 return “The result is a tie!”} 13 if (choice1 = “rock”) { 14 if (choice2 = “scissors”) { 15 return “rock wins”; 16 } else { 17 return “paper wins”; 18 } 19 } 20 };

Answer 524091c180ff33597f004aad

It means you try to assign a value whereas,in the same time, you try to compare these values. To compares two values it’s ‘==’ or ‘===’ . To assign a value to a variable it’s ‘=’

assignment in conditional expression javascript

It means you assign a value where you’re meant to compare two values.

Answer 524152b580ff33cfb10002ad

e.g. here instead of comparing choice2 to choice1 you assign choice2 to choice1, the problem is that this operation has sideeffects, the statement choice1 = choice2 itself has the value of choice2 and as all non-empty strings are treated as true if they are used in a condition you will have an unexpected behaviour and as this happens often unintended you get a warning.

Also check the link clarisse mentioned to see the difference between == and ===.

Answer 52438a6e548c35c358000e68

We may as well all chime in on this one. :)

FAQs, Errors, Explanations and Reviews has a short section on this (maybe too short?).

assignment in conditional expression javascript

Popular free courses

Learn javascript.

  • Using Oracle Business Intelligence or Oracle Analytics for Oracle Taleo Enterprise Edition

Conditional Expressions

Expressions are building blocks for creating conditional expressions that convert a value from one form to another.

CASE (Switch)

This form of the CASE statement is also referred to as the CASE(Lookup) form. The value of expr1 is examined, then the WHEN expressions. If expr1 matches any WHEN expression, it assigns the value in the corresponding THEN expression.

If none of the WHEN expressions match, it assigns the default value specified in the ELSE expression. If no ELSE expression is specified, the system automatically adds an ELSE NULL .

If expr1 matches an expression in multiple WHEN clauses, only the expression following the first match is assigned.

CASE starts the CASE statement. Must be followed by an expression and one or more WHEN and THEN statements, an optional ELSE statement, and the END keyword.

WHEN specifies the condition to be satisfied.

THEN specifies the value to assign if the corresponding WHEN expression is satisfied.

ELSE specifies the value to assign if none of the WHEN conditions are satisfied. If omitted, ELSE NULL is assumed.

END ends the CASE statement.

In this example, the WHEN statements must reflect a strict equality. For example, a WHEN condition of WHEN < 0 THEN 'Under Par' is illegal because comparison operators are not allowed.

This form of the CASE statement evaluates each WHEN condition and if satisfied, assigns the value in the corresponding THEN expression.

If none of the WHEN conditions are satisfied, it assigns the default value specified in the ELSE expression. If no ELSE expression is specified, the system automatically adds an ELSE NULL .

CASE starts the CASE statement. Must be followed by one or more WHEN and THEN statements, an optional ELSE statement, and the END keyword.

Unlike the Switch form of the CASE statement, the WHEN statements in the If form allow comparison operators. For example, a WHEN condition of WHEN < 0 THEN 'Under Par' is legal.

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

Unconditional use of conditional expression for default assignment

I'm getting the following linting error: Unconditional use of conditional expression for default assignment

What is wrong with the below?

Where if myOverride is defined I want to use myOverride, if it is not defined I want to use the env var MAGIC_HOST .

halfer's user avatar

  • 3 How is that expression actually used? Like, where does it appear in the code? –  Pointy Commented Jan 22, 2018 at 19:43
  • Define "not defined". Not declared at all? Declared but with the value undefined ? Declared and you want all falsy values to be replaced with MAGIC_HOST ? –  T.J. Crowder Commented Jan 22, 2018 at 19:45

3 Answers 3

Apparently you're using ESLint (as that error is an ESLint) error. It's because of the no-unneeded-ternary rule which is meant to flag up unnecessary use of the conditional operator (they call it the "ternary")¹. From the linked docs:

Another common mistake is using a single variable as both the conditional test and the consequent. In such cases, the logical OR can be used to provide the same functionality. Here is an example: // Bad var foo = bar ? bar : 1; // Good var foo = bar || 1;

So the rule is telling you to use myOverride || MAGIC_HOST instead.²

You don't have to, the code you've shown isn't wrong . It's just it doesn't pass that ESLint rule.

¹ "they call it the 'ternary'" - The conditional operator is a ternary operator (an operator accepting three operands, just like * is a binary operator — an operator accepting two operands). And it is, for now , the only ternary operator JavaScript has. But that doesn't necessarily always have to be true as the language evolves. It's correctly called the conditional operator .

² Depending on what the valid values for myOverride are, you may or may not want myOverride ?? MAGIC_HOST these days. The difference is that with ?? , only the values null and undefined are replaced with MAGIC_HOST , but with || any falsy value is replaced with MAGIC_HOST . For a string, you may want to stick with || , but it's good to know your options.

T.J. Crowder's user avatar

It is not inherently wrong , but it is better written as:

as explained here .

Oro's user avatar

Little bit safer is to use : nullish operator ?? instead of a logical operator ||

DuFuS's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

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

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • PWM Dimming of a Low-Voltage DC Incandescent Filament (Thermal Shock?)
  • Is it better to show fake sympathy to maintain a good atmosphere?
  • Single author or joint paper with a famous author?
  • Book that I read around 1975, where the main character is a retired space pilot hired to steal an object from a lab called Menlo Park
  • Artinian Gorenstein subrings with same socle degree
  • What is the translation of misgendering in French?
  • Can front gear be replaced on a Retrospec Judd folding bicycle?
  • What’s the highest salary the greedy king can arrange for himself?
  • Do Christians believe that Jews and Muslims go to hell?
  • Is Légal’s reported “psychological trick” considered fair play or unacceptable conduct under FIDE rules?
  • What does ‘a grade-hog’ mean?
  • Does free multiplicative convolution become free additive convolution under logarithm?
  • Ceramic capacitor has no voltage rating, recommendations?
  • Does concentrating on a different spell end a concentration spell?
  • Are comments obsolete in favor of Generative AI?
  • Where is the phase shift on this oscillator?
  • How to produce this table: Probability datatable with multirow
  • Does this double well potential contradict the fact that there is no degeneracy for one-dimensional bound states?
  • Cloud masking ECOSTRESS LST data
  • Specific calligraphic font for lowercase g
  • Are there examples of triple entendres in English?
  • Geometry question about a six-pack of beer
  • Event sourcing javascript implementation
  • How to engagingly introduce a ton of history that happens in, subjectively, a moment?

assignment in conditional expression javascript

IMAGES

  1. Conditional Operator in JavaScript

    assignment in conditional expression javascript

  2. 35 Conditional Expression In Javascript

    assignment in conditional expression javascript

  3. Writing better conditional expressions in JavaScript

    assignment in conditional expression javascript

  4. Basic JavaScript Exercise

    assignment in conditional expression javascript

  5. JavaScript Conditional Statement || Learn Javascript Online

    assignment in conditional expression javascript

  6. Conditional Expressions In JavaScript || Advanced JavaScript Course 04

    assignment in conditional expression javascript

VIDEO

  1. Java Script Logical Operator Lesson # 08

  2. Javascript

  3. 26. Module :Programmer en JavaScript |Secteur : Digital & IA |الجافاسكريبت من البداية إلى الإحتراف

  4. 28. Module :Programmer en JavaScript |Secteur : Digital & IA |الجافاسكريبت من البداية إلى الإحتراف

  5. 11. Javascript Conditional Statement If

  6. #coding for Conditional Expression🙏🏻🙏🏻

COMMENTS

  1. javascript

    4. = is assignment, but in conditional statements you need to check for equality ( == ), check if something is greater ( > ), check if something is less ( <) etc. You are assigning the variable j the length of myName rather than checking some condition on this line: for(var j = i;j = myName.length;){. Instead you probably need to do something ...

  2. Conditional (ternary) operator

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

  3. How to Use the Ternary Operator in JavaScript

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

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

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

  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. Assignment (=)

    The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...

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

  9. JavaScript if...else Statement (with Examples)

    The JavaScript if...else statement is used to execute/skip a block of code based on a condition. Here's a quick example of the if...else statement. You can read the rest of the tutorial if you want to learn about if...else in greater detail. Example. let score = 45;

  10. Conditional branching: if,

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

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

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

  14. Expressions and operators

    Expressions and operators. This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. A complete and detailed list of operators and expressions is also available in the reference.

  15. if...else

    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. To execute multiple statements, use a block statement ({ /* ... */ }) to group those statements.To execute no statements, use an empty statement.. statement2

  16. What does "assignment in conditional expression" mean?

    It means you try to assign a value whereas,in the same time, you try to compare these values. To compares two values it's '==' or '===' . To assign a value to a variable it's '='. It means you assign a value where you're meant to compare two values.

  17. Expressions and operators

    Basic keywords and general expressions in JavaScript. These expressions have the highest precedence (higher than operators ). The this keyword refers to a special property of an execution context. Basic null, boolean, number, and string literals. Array initializer/literal syntax. Object initializer/literal syntax.

  18. Conditional Expressions

    Expressions are building blocks for creating conditional expressions that convert a value from one form to another. CASE (Switch) This form of the CASE statement is also referred to as the CASE(Lookup) form. The value of expr1 is examined, then the WHEN expressions. If expr1 matches any WHEN expression, it assigns the value in the corresponding THEN expression.

  19. javascript

    javascript: If-statement - Expected an assignment or function call and instead saw an expression 3 Expected an assignment or function and instead saw an expression

  20. javascript

    Here is an example: So the rule is telling you to use myOverride || MAGIC_HOST instead.². You don't have to, the code you've shown isn't wrong. It's just it doesn't pass that ESLint rule. ¹ "they call it the 'ternary'" - The conditional operator is a ternary operator (an operator accepting three operands, just like * is a binary operator ...

  21. Regular expressions

    Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), replaceAll(), search(), and split() methods of String. This chapter describes JavaScript regular expressions. It provides a brief overview of each ...