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

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

  • 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 Assignment Operators

JavaScript Assignment Operators

Summary : in this tutorial, you will learn how to use JavaScript assignment operators to assign a value to a variable.

Introduction to JavaScript assignment operators

An assignment operator ( = ) assigns a value to a variable. The syntax of the assignment operator is as follows:

In this syntax, JavaScript evaluates the expression b first and assigns the result to the variable a .

The following example declares the counter variable and initializes its value to zero:

The following example increases the counter variable by one and assigns the result to the counter variable:

When evaluating the second statement, JavaScript evaluates the expression on the right-hand first ( counter + 1 ) and assigns the result to the counter variable. After the second assignment, the counter variable is 1 .

To make the code more concise, you can use the += operator like this:

In this syntax, you don’t have to repeat the counter variable twice in the assignment.

The following table illustrates assignment operators that are shorthand for another operator and the assignment:

OperatorMeaningDescription
Assigns the value of to .
Assigns the result of plus to .
Assigns the result of minus to .
Assigns the result of times to .
Assigns the result of divided by to .
Assigns the result of modulo to .
Assigns the result of AND to .
Assigns the result of OR to .
Assigns the result of XOR to .
Assigns the result of shifted left by to .
Assigns the result of shifted right (sign preserved) by to .
Assigns the result of shifted right by to .

Chaining JavaScript assignment operators

If you want to assign a single value to multiple variables, you can chain the assignment operators. For example:

In this example, JavaScript evaluates from right to left. Therefore, it does the following:

  • Use the assignment operator ( = ) to assign a value to a variable.
  • Chain the assignment operators if you want to assign a single value to multiple variables.

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

Stone/Cavan Images/Getty Images

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

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

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

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

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

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

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

Ternary Operator Example

Let's look at a real example.

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

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

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

Multiple Evaluations

You can include multiple evaluations, as well:

Multiple Operations

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

Ternary Operator Implications

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

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

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

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

JS Tutorial

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

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

The Assignment Operator = assigns values

The Addition Operator + adds values

The Multiplication Operator * multiplies values

The Comparison Operator > compares values

JavaScript Assignment

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

Assignment Examples

Javascript addition.

The Addition Operator ( + ) adds numbers:

JavaScript Multiplication

The Multiplication Operator ( * ) multiplies numbers:

Multiplying

Types of javascript operators.

There are different types of JavaScript operators:

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

JavaScript Arithmetic Operators

Arithmetic Operators are used to perform arithmetic on numbers:

Arithmetic Operators Example

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

Arithmetic operators are fully described in the JS Arithmetic chapter.

Advertisement

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

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

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

Assignment operators are fully described in the JS Assignment chapter.

JavaScript Comparison Operators

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

Comparison operators are fully described in the JS Comparisons chapter.

JavaScript String Comparison

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

Note that strings are compared alphabetically:

JavaScript String Addition

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

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

The result of text1 will be:

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

Adding Strings and Numbers

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

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

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

JavaScript Logical Operators

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

Logical operators are fully described in the JS Comparisons chapter.

JavaScript Type Operators

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

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

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

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

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

Bitwise operators are fully described in the JS Bitwise chapter.

Test Yourself With Exercises

Multiply 10 with 5 , and alert the result.

Start the Exercise

Test Yourself with Exercises!

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

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

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

Assignment in conditional expression

I am trying to learn JavaScript at Codecademy. I am working on this problem about for loops, and I can't figure out what is wrong with my code. It says "Assignment in conditional expression," but I don't know what that means. It is saying the error is at the second for statement.

The goal is to change the value of hits to however many times my name was included in the text variable string.

Here is my code:

var text ="Max Gee Max Gee Max Gee"; var myName = "Max"; var hits=[]; for(var i=0;i<text.length;i++){ if(text[i]==="M"){ for(var j = i;j = myName.length;){ hits.push("Max"); } } }

  • compiler-errors

Braiam's user avatar

  • 1 What is the assignment supposed to do? Conditional as in if . –  Elliott Frisch Commented Dec 15, 2013 at 6:38
  • 1 give the link of the assignment –  Atish Kumar Dipongkor Commented Dec 15, 2013 at 6:39
  • 1 @AtishDipongkor codecademy.com/courses/javascript-beginner-en-XEDZA/0/… –  maxgee Commented Dec 15, 2013 at 6:40
  • @ElliottFrisch Overall it is supposed to change hits to how many time my name was in the var text –  maxgee Commented Dec 15, 2013 at 6:48
  • @hicurin Edited and it is now included. –  maxgee Commented Dec 15, 2013 at 6:50

4 Answers 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:

Instead you probably need to do something like this:

However, this may not necessarily be the solution to your Codecademy Assignment, but it will solve your specific javascript error. play around with and read up on < , > , == and the other conditionals mentioned here to try to figure out what works.

Edit: if you wanted a solution to your entire problem, it would have been helpful to post a link to the problem in the question and not only mention the specific error you were getting, but explain the entire question. That being said, you missed a few things here:

  • You were doing assignment instead of checking a condition as I explained above.
  • You forgot to increment j in your for loop as Franklin mentioned in the comments. You need to do j++ .
  • You are not stopping at the correct point in the string. As Codecademy says, "...your second for loop should stop when it reaches its current point in the string + myName.length ." This means that you need to stop at text.length + myName.length instead of just myName.length . That also means you should use < rather than <= as I recommended above.

Putting all of that together, the solution is to put this line:

in place of of this line:

stiemannkj1's user avatar

  • Alright I changed it to this and this is what codecademy is saying: Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length. –  maxgee Commented Dec 15, 2013 at 6:44
  • I edited my answer and tried to give a little more explanation. –  stiemannkj1 Commented Dec 15, 2013 at 7:02
  • @maxgee, I edited my answer to include the solution. –  stiemannkj1 Commented Dec 15, 2013 at 7:18

Change it to for (var j = i; j === myName.length; ) {

You're using an assignment where you should be using a conditional/boolean.

sbking's user avatar

  • I changed it to that and the website told me this back: Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length. –  maxgee Commented Dec 15, 2013 at 6:46

Tom Seidel's user avatar

I was struggling that also and finally I've understood, what codecademy are saying: ".. its current point in the string + myName.length" Just need to add myName.length.

and by the way text's and myName's content should start both same letter. Hope I am right and hope it helps!

Aleksei Kovalchuk'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 for-loop compiler-errors or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Is there mathematical significance to the LaGuardia floor tiles?
  • Getting lost on a Circular Track
  • Book that features clones used for retirement
  • How can I use the word 魅力的?
  • Why are some Cloudflare challenges CPU intensive?
  • Does my employer contributions count towards the Roth limit of $7k?Roth contributions
  • Identify this 6 pin IC
  • When should I put a biasing resistor - op-amps
  • How much technological progress could a group of modern people make in a century?
  • Why are my empty files not being assigned the correct mimetype?
  • Was using an older version of a legal card from a nonlegal set ever not legal?
  • Where to put acknowledgments in a math paper
  • Why is resonance such a widespread phenomenon?
  • Big Transition of Binary Counting in perspective of IEEE754 floating point
  • Why is so much of likelihood theory focused on solving the score function equation?
  • Paying a parking fine when I don't trust the recipient
  • What would the natural diet of Bigfoot be?
  • How to make conditions work in Which?
  • What film is it where the antagonist uses an expandable triple knife?
  • What is the unit for 'magnitude' in terms of the Isophotal diameter of a galaxy?
  • Did Queen (or Freddie Mercury) really not like Star Wars?
  • Why is the area covered by 1 steradian (in a sphere) circular in shape?
  • Was Willy Wonka correct when he accused Charlie of stealing Fizzy Lifting Drinks?
  • Is it feasible to create an online platform to effectively teach college-level math (abstract algebra, real analysis, etc.)?

javascript var conditional assignment

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Optional chaining (?.)

The optional chaining ( ?. ) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null , the expression short circuits and evaluates to undefined instead of throwing an error.

Description

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish ( null or undefined ), the expression short-circuits with a return value of undefined . When used with function calls, it returns undefined if the given function does not exist.

This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.

For example, consider an object obj which has a nested structure. Without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as:

The value of obj.first is confirmed to be non- null (and non- undefined ) before accessing the value of obj.first.second . This prevents the error that would occur if you accessed obj.first.second directly without testing obj.first .

This is an idiomatic pattern in JavaScript, but it gets verbose when the chain is long, and it's not safe. For example, if obj.first is a Falsy value that's not null or undefined , such as 0 , it would still short-circuit and make nestedProp become 0 , which may not be desirable.

With the optional chaining operator ( ?. ), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second :

By using the ?. operator instead of just . , JavaScript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second . If obj.first is null or undefined , the expression automatically short-circuits, returning undefined .

This is equivalent to the following, except that the temporary variable is in fact not created:

Optional chaining cannot be used on a non-declared root object, but can be used with a root object with value undefined .

Optional chaining with function calls

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

Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found:

However, if there is a property with such a name which is not a function, using ?. will still raise a TypeError exception "someInterface.customMethod is not a function".

Note: If someInterface itself is null or undefined , a TypeError exception will still be raised ("someInterface is null"). If you expect that someInterface itself may be null or undefined , you have to use ?. at this position as well: someInterface?.customMethod?.() .

eval?.() is the shortest way to enter indirect eval mode.

Optional chaining with expressions

You can also use the optional chaining operator with bracket notation , which allows passing an expression as the property name:

This is particularly useful for arrays, since array indices must be accessed with square brackets.

Invalid optional chaining

It is invalid to try to assign to the result of an optional chaining expression:

Template literal tags cannot be an optional chain (see SyntaxError: tagged template cannot be used with optional chain ):

The constructor of new expressions cannot be an optional chain (see SyntaxError: new keyword cannot be used with an optional chain ):

Short-circuiting

When using optional chaining with expressions, if the left operand is null or undefined , the expression will not be evaluated. For instance:

Subsequent property accesses will not be evaluated either.

This is equivalent to:

However, this short-circuiting behavior only happens along one continuous "chain" of property accesses. If you group one part of the chain, then subsequent property accesses will still be evaluated.

Except the temp variable isn't created.

Basic example

This example looks for the value of the name property for the member bar in a map when there is no such member. The result is therefore undefined .

Dealing with optional callbacks or event handlers

If you use callbacks or fetch methods from an object with a destructuring assignment , you may have non-existent values that you cannot call as functions unless you have tested their existence. Using ?. , you can avoid this extra test:

Stacking the optional chaining operator

With nested structures, it is possible to use optional chaining multiple times:

Combining with the nullish coalescing operator

The nullish coalescing operator may be used after optional chaining in order to build a default value when none was found:

Specifications

Specification

Browser compatibility

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

  • Nullish coalescing operator ( ?? )

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

  3. Making decisions in your code

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

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

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

  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. JavaScript If-Else and If-Then

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

  8. if...else

    else. statement2. condition. An expression that is considered to be either truthy or falsy. statement1. Statement that is executed if condition is truthy. Can be any statement, including further nested if statements. To execute multiple statements, use a block statement ({ /* ... */ }) to group those statements.

  9. Conditional Statements in JavaScript

    Destructuring assignment allows us to assign the properties of an array or object to a bunch of variables that are sometimes very convenient and short. Consider the following illustration. Both of the below-mentioned methods are right and produce the same result. Without Destructuring: var array = [1, 20, 40]; var first = array[0] var second = arra

  10. JavaScript Assignment Operators

    An assignment operator (=) assigns a value to a variable. The syntax of the assignment operator is as follows: let a = b; Code language: JavaScript (javascript) In this syntax, JavaScript evaluates the expression b first and assigns the result to the variable a. The following example declares the counter variable and initializes its value to zero:

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

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

  12. javascript

    I would like to know a simplest and best way to assign a value to a variable if other variable is not null/undefined. This isn't the shortest and most elegant way possible ... Javascript, conditional variable via function. 0. Assign value in javascript. 2. How to assign varaible in ng-model on input based on condition. 1.

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

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

  15. JavaScript if/else Statement

    The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions. In JavaScript we have the following conditional ...

  16. JavaScript Operators

    Javascript operators are used to perform different types of mathematical and logical computations. Examples: The Assignment Operator = assigns values. The Addition Operator + adds values. The Multiplication Operator * multiplies values. The Comparison Operator > compares values

  17. JavaScript OR (||) variable assignment explanation

    The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages. The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned. For example: "foo" || "bar"; // returns "foo".

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

  19. 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 like this:

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

  21. Optional chaining (?.)

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