Home » JavaScript Tutorial » JavaScript Logical Assignment Operators

JavaScript Logical Assignment Operators

Summary : in this tutorial, you’ll learn about JavaScript logical assignment operators, including the logical OR assignment operator ( ||= ), the logical AND assignment operator ( &&= ), and the nullish assignment operator ( ??= ).

ES2021 introduces three logical assignment operators including:

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

The following table shows the equivalent of the logical assignments operator:

Logical Assignment OperatorsLogical Operators
x ||= yx || (x = y)
x &&= yx && (x = y)
x ??= yx ?? (x = y);

The Logical OR assignment operator

The logical OR assignment operator ( ||= ) accepts two operands and assigns the right operand to the left operand if the left operand is falsy:

In this syntax, the ||= operator only assigns y to x if x is falsy. For example:

In this example, the title variable is undefined , therefore, it’s falsy. Since the title is falsy, the operator ||= assigns the 'untitled' to the title . The output shows the untitled as expected.

See another example:

In this example, the title is 'JavaScript Awesome' so it is truthy. Therefore, the logical OR assignment operator ( ||= ) doesn’t assign the string 'untitled' to the title variable.

The logical OR assignment operator:

is equivalent to the following statement that uses the logical OR operator :

Like the logical OR operator, the logical OR assignment also short-circuits. It means that the logical OR assignment operator only performs an assignment when the x is falsy.

The following example uses the logical assignment operator to display a default message if the search result element is empty:

The Logical AND assignment operator

The logical AND assignment operator only assigns y to x if x is truthy:

The logical AND assignment operator also short-circuits. It means that

is equivalent to:

The following example uses the logical AND assignment operator to change the last name of a person object if the last name is truthy:

The nullish coalescing assignment operator

The nullish coalescing assignment operator only assigns y to x if x is null or undefined :

It’s equivalent to the following statement that uses the nullish coalescing operator :

The following example uses the nullish coalescing assignment operator to add a missing property to an object:

In this example, the user.nickname is undefined , therefore, it’s nullish. The nullish coalescing assignment operator assigns the string 'anonymous' to the user.nickname property.

The following table illustrates how the logical assignment operators work:

  • The logical OR assignment ( x ||= y ) operator only assigns y to x if x is falsy.
  • The logical AND assignment ( x &&= y ) operator only assigns y to x if x is truthy.
  • The nullish coalescing assignment ( x ??= y ) operator only assigns y to x if x is nullish.
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Logical OR assignment (||=)

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

Description

Logical OR assignment short-circuits , meaning that x ||= y is equivalent to x || (x = y) , except that the expression x is only evaluated once.

No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const :

Neither would the following trigger the setter:

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

Setting default content

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

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

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

Specifications

Specification

Logical operators

There are four logical operators in JavaScript: || (OR), && (AND), ! (NOT), ?? (Nullish Coalescing). Here we cover the first three, the ?? operator is in the next article.

Although they are called “logical”, they can be applied to values of any type, not only boolean. Their result can also be of any type.

Let’s see the details.

The “OR” operator is represented with two vertical line symbols:

In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are true , it returns true , otherwise it returns false .

In JavaScript, the operator is a little bit trickier and more powerful. But first, let’s see what happens with boolean values.

There are four possible logical combinations:

As we can see, the result is always true except for the case when both operands are false .

If an operand is not a boolean, it’s converted to a boolean for the evaluation.

For instance, the number 1 is treated as true , the number 0 as false :

Most of the time, OR || is used in an if statement to test if any of the given conditions is true .

For example:

We can pass more conditions:

OR "||" finds the first truthy value

The logic described above is somewhat classical. Now, let’s bring in the “extra” features of JavaScript.

The extended algorithm works as follows.

Given multiple OR’ed values:

The OR || operator does the following:

  • Evaluates operands from left to right.
  • For each operand, converts it to boolean. If the result is true , stops and returns the original value of that operand.
  • If all operands have been evaluated (i.e. all were false ), returns the last operand.

A value is returned in its original form, without the conversion.

In other words, a chain of OR || returns the first truthy value or the last one if no truthy value is found.

For instance:

This leads to some interesting usage compared to a “pure, classical, boolean-only OR”.

Getting the first truthy value from a list of variables or expressions.

For instance, we have firstName , lastName and nickName variables, all optional (i.e. can be undefined or have falsy values).

Let’s use OR || to choose the one that has the data and show it (or "Anonymous" if nothing set):

If all variables were falsy, "Anonymous" would show up.

Short-circuit evaluation.

Another feature of OR || operator is the so-called “short-circuit” evaluation.

It means that || processes its arguments until the first truthy value is reached, and then the value is returned immediately, without even touching the other argument.

The importance of this feature becomes obvious if an operand isn’t just a value, but an expression with a side effect, such as a variable assignment or a function call.

In the example below, only the second message is printed:

In the first line, the OR || operator stops the evaluation immediately upon seeing true , so the alert isn’t run.

Sometimes, people use this feature to execute commands only if the condition on the left part is falsy.

&& (AND)

The AND operator is represented with two ampersands && :

In classical programming, AND returns true if both operands are truthy and false otherwise:

An example with if :

Just as with OR, any value is allowed as an operand of AND:

AND “&&” finds the first falsy value

Given multiple AND’ed values:

The AND && operator does the following:

  • For each operand, converts it to a boolean. If the result is false , stops and returns the original value of that operand.
  • If all operands have been evaluated (i.e. all were truthy), returns the last operand.

In other words, AND returns the first falsy value or the last value if none were found.

The rules above are similar to OR. The difference is that AND returns the first falsy value while OR returns the first truthy one.

We can also pass several values in a row. See how the first falsy one is returned:

When all values are truthy, the last value is returned:

The precedence of AND && operator is higher than OR || .

So the code a && b || c && d is essentially the same as if the && expressions were in parentheses: (a && b) || (c && d) .

Sometimes, people use the AND && operator as a "shorter way to write if ".

The action in the right part of && would execute only if the evaluation reaches it. That is, only if (x > 0) is true.

So we basically have an analogue for:

Although, the variant with && appears shorter, if is more obvious and tends to be a little bit more readable. So we recommend using every construct for its purpose: use if if we want if and use && if we want AND.

The boolean NOT operator is represented with an exclamation sign ! .

The syntax is pretty simple:

The operator accepts a single argument and does the following:

  • Converts the operand to boolean type: true/false .
  • Returns the inverse value.

A double NOT !! is sometimes used for converting a value to boolean type:

That is, the first NOT converts the value to boolean and returns the inverse, and the second NOT inverses it again. In the end, we have a plain value-to-boolean conversion.

There’s a little more verbose way to do the same thing – a built-in Boolean function:

The precedence of NOT ! is the highest of all logical operators, so it always executes first, before && or || .

What's the result of OR?

What is the code below going to output?

The answer is 2 , that’s the first truthy value.

What's the result of OR'ed alerts?

What will the code below output?

The answer: first 1 , then 2 .

The call to alert does not return a value. Or, in other words, it returns undefined .

  • The first OR || evaluates its left operand alert(1) . That shows the first message with 1 .
  • The alert returns undefined , so OR goes on to the second operand searching for a truthy value.
  • The second operand 2 is truthy, so the execution is halted, 2 is returned and then shown by the outer alert.

There will be no 3 , because the evaluation does not reach alert(3) .

What is the result of AND?

What is this code going to show?

The answer: null , because it’s the first falsy value from the list.

What is the result of AND'ed alerts?

What will this code show?

The answer: 1 , and then undefined .

The call to alert returns undefined (it just shows a message, so there’s no meaningful return).

Because of that, && evaluates the left operand (outputs 1 ), and immediately stops, because undefined is a falsy value. And && looks for a falsy value and returns it, so it’s done.

The result of OR AND OR

What will the result be?

The answer: 3 .

The precedence of AND && is higher than || , so it executes first.

The result of 2 && 3 = 3 , so the expression becomes:

Now the result is the first truthy value: 3 .

Check the range between

Write an if condition to check that age is between 14 and 90 inclusively.

“Inclusively” means that age can reach the edges 14 or 90 .

Check the range outside

Write an if condition to check that age is NOT between 14 and 90 inclusively.

Create two variants: the first one using NOT ! , the second one – without it.

The first variant:

The second variant:

A question about "if"

Which of these alert s are going to execute?

What will the results of the expressions be inside if(...) ?

The answer: the first and the third will execute.

Check the login

Write the code which asks for a login with prompt .

If the visitor enters "Admin" , then prompt for a password, if the input is an empty line or Esc – show “Canceled”, if it’s another string – then show “I don’t know you”.

The password is checked as follows:

  • If it equals “TheMaster”, then show “Welcome!”,
  • Another string – show “Wrong password”,
  • For an empty string or cancelled input, show “Canceled”

The schema:

Please use nested if blocks. Mind the overall readability of the code.

Hint: passing an empty input to a prompt returns an empty string '' . Pressing ESC during a prompt returns null .

Run the demo

Note the vertical indents inside the if blocks. They are technically not required, but make the code more readable.

Lesson navigation

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

Learn JavaScript Operators – Logical, Comparison, Ternary, and More JS Operators With Examples

Nathan Sebhastian

JavaScript has many operators that you can use to perform operations on values and variables (also called operands)

Based on the types of operations these JS operators perform, we can divide them up into seven groups:

Arithmetic Operators

Assignment operators, comparison operators, logical operators.

  • Ternary Operators

The typeof Operator

Bitwise operators.

In this handbook, you're going to learn how these operators work with examples. Let's start with arithmetic operators.

The arithmetic operators are used to perform mathematical operations like addition and subtraction.

These operators are frequently used with number data types, so they are similar to a calculator. The following example shows how you can use the + operator to add two variables together:

Here, the two variables x and y are added together using the plus + operator. We also used the console.log() method to print the result of the operation to the screen.

You can use operators directly on values without assigning them to any variable too:

In JavaScript, we have 8 arithmetic operators in total. They are:

  • Subtraction -
  • Multiplication *
  • Remainder %
  • Exponentiation **
  • Increment ++
  • Decrement --

Let's see how these operators work one by one.

1. Addition operator

The addition operator + is used to add two or more numbers together. You've seen how this operator works previously, but here's another example:

You can use the addition operator on both integer and floating numbers.

2. Subtraction operator

The subtraction operator is marked by the minus sign − and you can use it to subtract the right operand from the left operand.

For example, here's how to subtract 3 from 5:

3. Multiplication operator

The multiplication operator is marked by the asterisk * symbol, and you use it to multiply the value on the left by the value on the right of the operator.

4. Division operator

The division operator / is used to divide the left operand by the right operand. Here are some examples of using the operator:

5. Remainder operator

The remainder operator % is also known as the modulo or modulus operator. This operator is used to calculate the remainder after a division has been performed.

A practical example should make this operator easier to understand, so let's see one:

The number 10 can't be divided by 3 perfectly. The result of the division is 3 with a remainder of 1. The remainder operator simply returns that remainder number.

If the left operand can be divided with no remainder, then the operator returns 0.

This operator is commonly used when you want to check if a number is even or odd. If a number is even, dividing it by 2 will result in a remainder of 0, and if it's odd, the remainder will be 1.

6. Exponentiation operator

The exponentiation operator is marked by two asterisks ** . It's one of the newer JavaScript operators and you can use it to calculate the power of a number (based on its exponent).

For example, here's how to calculate 10 to the power of 3:

Here, the number 10 is multiplied by itself 3 times (10 10 10)

The exponentiation operator gives you an easy way to find the power of a specific number.

7. Increment operator

The increment ++ operator is used to increase the value of a number by one. For example:

This operator gives you a faster way to increase a variable value by one. Without the operator, here's how you increment a variable:

Using the increment operator allows you to shorten the second line. You can place this operator before or next to the variable you want to increment:

Both placements shown above are valid. The difference between prefix (before) and postfix (after) placements is that the prefix position will execute the operator after that line of code has been executed.

Consider the following example:

Here, you can see that placing the increment operator next to the variable will print the variable as if it has not been incremented.

When you place the operator before the variable, then the number will be incremented before calling the console.log() method.

8. Decrement operator

The decrement -- operator is used to decrease the value of a number by one. It's the opposite of the increment operator:

Please note that you can only use increment and decrement operators on a variable. An error occurs when you try to use these operators directly on a number value:

You can't use increment or decrement operator on a number directly.

Arithmetic operators summary

Now you've learned the 8 types of arithmetic operators. Excellent! Keep in mind that you can mix these operators to perform complex mathematical equations.

For example, you can perform an addition and multiplication on a set of numbers:

The order of operations in JavaScript is the same as in mathematics. Multiplication, division, and exponentiation take a higher priority than addition or subtraction (remember that acronym PEMDAS? Parentheses, exponents, multiplication and division, addition and subtraction – there's your order of operations).

You can use parentheses () to change the order of the operations. Wrap the operation you want to execute first as follows:

When using increment or decrement operators together with other operators, you need to place the operators in a prefix position as follows:

This is because a postfix increment or decrement operator will not be executed together with other operations in the same line, as I have explained previously.

Let's try some exercises. Can you guess the result of these operations?

And that's all for arithmetic operators. You've done a wonderful job learning about these operators.

Let's take a short five-minute break before proceeding to the next type of operators.

The second group of operators we're going to explore is the assignment operators.

Assignment operators are used to assign a specific value to a variable. The basic assignment operator is marked by the equal = symbol, and you've already seen this operator in action before:

After the basic assignment operator, there are 5 more assignment operators that combine mathematical operations with the assignment. These operators are useful to make your code clean and short.

For example, suppose you want to increment the x variable by 2. Here's how you do it with the basic assignment operator:

There's nothing wrong with the code above, but you can use the addition assignment += to rewrite the second line as follows:

There are 7 kinds of assignment operators that you can use in JavaScript:

NameOperation exampleMeaning
Assignment
Addition assignment
Subtraction assignment
Multiplication assignment
Division assignment
Remainder assignment
Exponentiation assignment

The arithmetic operators you've learned in the previous section can be combined with the assignment operator except the increment and decrement operators.

Let's have a quick exercise. Can you guess the results of these assignments?

Now you've learned about assignment operators. Let's continue and learn about comparison operators.

As the name implies, comparison operators are used to compare one value or variable with something else. The operators in this category always return a boolean value: either true or false .

For example, suppose you want to compare if a variable's value is greater than 1. Here's how you do it:

The greater than > operator checks if the value on the left operand is greater than the value on the right operand.

There are 8 kinds of comparison operators available in JavaScript:

NameOperation exampleMeaning
Equal Returns if the operands are equal
Not equal Returns if the operands are not equal
Strict equal Returns if the operands are equal and have the same type
Strict not equal Returns if the operands are not equal, or have different types
Greater than Returns if the left operand is greater than the right operand
Greater than or equal Returns if the left operand is greater than or equal to the right operand
Less than Returns if the left operand is less than the right operand
Less than or equal Returns if the left operand is less than or equal to the right operand

Here are some examples of using comparison operators:

The comparison operators are further divided in two types: relational and equality operators.

The relational operators compare the value of one operand relative to the second operand (greater than, less than)

The equality operators check if the value on the left is equal to the value on the right. They can also be used to compare strings like this:

String comparisons are case-sensitive, as shown in the example above.

JavaScript also has two versions of the equality operators: loose and strict.

In strict mode, JavaScript will compare the values without performing a type coercion. To enable strict mode, you need to add one more equal = symbol to the operation as follows:

Since type coercion might result in unwanted behavior, you should use the strict equality operators anytime you do an equality comparison.

Logical operators are used to check whether one or more expressions result in either true or false .

There are three logical operators available in JavaScript:

NameOperation exampleMeaning
Logical AND Returns if all operands are , else returns
Logical OR`xy`Returns if one of the operands is , else returns
Logical NOT Reverse the result: returns if and vice versa

These operators can only return Boolean values. For example, you can determine whether '7 is greater than 2' and '5 is greater than 4':

These logical operators follow the laws of mathematical logic:

  • && AND operator – if any expression returns false , the result is false
  • || OR operator – if any expression returns true , the result is true
  • ! NOT operator – negates the expression, returning the opposite.

Let's do a little exercise. Try to run these statements on your computer. Can you guess the results?

These logical operators will come in handy when you need to assert that a specific requirement is fulfilled in your code.

Let's say a happyLife requires a job with highIncome and supportiveTeam :

Based on the requirements, you can use the logical AND operator to check whether you have both requirements. When one of the requirements is false , then happyLife equals false as well.

Ternary Operator

The ternary operator (also called the conditional operator) is the only JavaScipt operator that requires 3 operands to run.

Let's imagine you need to implement some specific logic in your code. Suppose you're opening a shop to sell fruit. You give a $3 discount when the total purchase is $20 or more. Otherwise, you give a $1 discount.

You can implement the logic using an if..else statement as follows:

The code above works fine, but you can use the ternary operator to make the code shorter and more concise as follows:

The syntax for the ternary operator is condition ? expression1 : expression2 .

You need to write the condition to evaluate followed by a question ? mark.

Next to the question mark, you write the expression to execute when the condition evaluates to true , followed by a colon : symbol. You can call this expression1 .

Next to the colon symbol, you write the expression to execute when the condition evaluates to false . This is expression2 .

As the example above shows, the ternary operator can be used as an alternative to the if..else statement.

The typeof operator is the only operator that's not represented by symbols. This operator is used to check the data type of the value you placed on the right side of the operator.

Here are some examples of using the operator:

The typeof operator returns the type of the data as a string. The 'number' type represents both integer and float types, the string and boolean represent their respective types.

Arrays, objects, and the null value are of object type, while undefined has its own type.

Bitwise operators are operators that treat their operands as a set of binary digits, but return the result of the operation as a decimal value.

These operators are rarely used in web development, so you can skip this part if you only want to learn practical stuff. But if you're interested to know how they work, then let me show you an example.

A computer uses a binary number system to store decimal numbers in memory. The binary system only uses two numbers, 0 and 1, to represent the whole range of decimal numbers we humans know.

For example, the decimal number 1 is represented as binary number 00000001, and the decimal number 2 is represented as 00000010.

I won't go into detail on how to convert a decimal number into a binary number as that's too much to include in this guide. The main point is that the bitwise operators operate on these binary numbers.

If you want to find the binary number from a specific decimal number, you can Google for the "decimal to binary calculator".

There are 7 types of bitwise operators in JavaScript:

  • Left Shift <<
  • Right Shift >>
  • Zero-fill Right Shift >>>

Let's see how they work.

1. Bitwise AND operator

The bitwise operator AND & returns a 1 when the number 1 overlaps in both operands. The decimal numbers 1 and 2 have no overlapping 1, so using this operator on the numbers return 0:

2. Bitwise OR operator

On the other hand, the bitwise operator OR | returns all 1s in both decimal numbers.

The binary number 00000011 represents the decimal number 3, so the OR operator above returns 3.

Bitwise XOR operator

The Bitwise XOR ^ looks for the differences between two binary numbers. When the corresponding bits are the same, it returns 0:

5 = 00000101

Bitwise NOT operator

Bitwise NOT ~ operator inverts the bits of a decimal number so 0 becomes 1 and 1 becomes 0:

Bitwise Left Shift operator

Bitwise Left Shift << shifts the position of the bit by adding zeroes from the right.

The excess bits are then discarded, changing the decimal number represented by the bits. See the following example:

The right operand is the number of zeroes you will add to the left operand.

Bitwise Right Shift operator

Bitwise Right Shift >> shifts the position of the bits by adding zeroes from the left. It's the opposite of the Left Shift operator:

Bitwise Zero-fill Right Shift operator

Also known as Unsigned Right Shift operator, the Zero-fill Right Shift >>> operator is used to shift the position of the bits to the right, while also changing the sign bit to 0 .

This operator transforms any negative number into a positive number, so you can see how it works when passing a negative number as the left operand:

In the above example, you can see that the >> and >>> operators return different results. The Zero-fill Right Shift operator has no effect when you use it on a positive number.

Now you've learned how the bitwise operators work. If you think they are confusing, then you're not alone! Fortunately, these operators are scarcely used when developing web applications.

You don't need to learn them in depth. It's enough to know what they are.

In this tutorial, you've learned the 7 types of JavaScript operators: Arithmetic, assignment, comparison, logical, ternary, typeof, and bitwise operators.

These operators can be used to manipulate values and variables to achieve a desired outcome.

Congratulations on finishing this guide!

If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book Beginning Modern JavaScript here .

beginning-js-cover

The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.

Here's my promise: You will actually feel like you understand what you're doing with JavaScript.

Until next time!

Read more posts .

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

home

JavaScript Tutorial

  • JavaScript Introduction
  • JavaScript Example
  • External JavaScript

JavaScript Basics

  • JS Variable
  • JS Global Variable
  • JS Data Types
  • JS Operators
  • JS If Statement
  • JS Function
  • JS Function - apply()
  • JS Function - bind()
  • JS Function - call()
  • JS Function - toString()

JavaScript Objects

Javascript bom.

  • Browser Objects
  • 1) Window Object
  • 2) History Object
  • 3) Navigator Object
  • 4) Screen Object

JavaScript DOM

  • 5) Document Object
  • getElementById
  • GetElementsByClassName()
  • getElementsByName
  • getElementsByTagName
  • JS innerHTML property
  • JS innerText property

JavaScript Validation

  • JS form validation
  • JS email validation

JavaScript OOPs

  • JS Prototype
  • JS constructor Method
  • JS static Method
  • JS Encapsulation
  • JS Inheritance
  • JS Polymorphism
  • JS Abstraction

JavaScript Cookies

  • Cookie Attributes
  • Cookie with multiple Name
  • Deleting Cookies
  • JavaScript Events
  • JavaScript addEventListener()
  • JS onclick event
  • JS dblclick event
  • JS onload event
  • JS onresize event

Exception Handling

  • JS Exception Handling
  • JavaScript try-catch

JavaScript Misc

  • JS this Keyword
  • JS Debugging
  • JS Hoisting
  • JS Strict Mode
  • JavaScript Promise
  • JS Compare dates
  • JavaScript array.length
  • JavaScript alert()
  • JavaScript eval() function
  • JavaScript closest()
  • JavaScript continue statement
  • JS getAttribute() method
  • JS hide elements
  • JavaScript prompt()
  • removeAttribute() method
  • JavaScript reset
  • JavaScript return
  • JS String split()
  • JS typeof operator
  • JS ternary operator
  • JS reload() method
  • JS setAttribute() method
  • JS setInterval() method
  • JS setTimeout() method
  • JS string includes() method
  • Calculate current week number in JavaScript
  • Calculate days between two dates in JavaScript
  • JavaScript String trim()
  • JavaScript timer
  • Remove elements from array
  • JavaScript localStorage
  • JavaScript offsetHeight
  • Confirm password validation
  • Static vs Const
  • How to Convert Comma Separated String into an Array in JavaScript
  • Calculate age using JavaScript
  • JavaScript label statement
  • JavaScript String with quotes
  • How to create dropdown list using JavaScript
  • How to disable radio button using JavaScript
  • Check if the value exists in Array in Javascript
  • Javascript Setinterval
  • JavaScript Debouncing
  • JavaScript print() method
  • JavaScript editable table

JavaScript Advance

  • JS TypedArray
  • JavaScript callback
  • JavaScript closures
  • JavaScript date difference
  • JavaScript date format
  • JS date parse() method
  • JavaScript defer
  • JavaScript redirect
  • JavaScript scope
  • JavaScript scroll
  • JavaScript sleep
  • JavaScript void
  • JavaScript Form

Differences

  • jQuery vs JavaScript
  • JavaScript vs PHP
  • Dart vs. JavaScript
  • JavaScript Vs. Angular Js
  • JavaScript vs. Node.js
  • How to add JavaScript to html
  • How to enable JavaScript in my browser
  • difference between Java and JavaScript
  • How to call JavaScript function in html
  • How to write a function in JavaScript
  • Is JavaScript case sensitive
  • How does JavaScript Work
  • How to debug JavaScript
  • How to Enable JavaScript on Android
  • What is a promise in JavaScript
  • What is hoisting in JavaScript
  • What is Vanilla JavaScript
  • How to add a class to an element using JavaScript
  • How to calculate the perimeter and area of a circle using JavaScript
  • How to create an image map in JavaScript
  • How to find factorial of a number in JavaScript
  • How to get the value of PI using JavaScript
  • How to make a text italic using JavaScript
  • What are the uses of JavaScript
  • How to get all checked checkbox value in JavaScript
  • How to open JSON file
  • Random image generator in JavaScript
  • How to add object in array using JavaScript
  • JavaScript Window open method
  • JavaScript Window close method
  • How to check a radio button using JavaScript
  • JavaScript Const
  • JavaScript function to check array is empty or not
  • JavaScript multi-line String
  • JavaScript Anonymous Functions
  • Implementing JavaScript Stack Using Array
  • JavaScript classList
  • JavaScript Code Editors
  • JavaScript let keyword
  • Random String Generator using JavaScript
  • JavaScript Queue
  • Event Bubbling and Capturing in JavaScript
  • How to select all checkboxes using JavaScript
  • JavaScript change Event
  • JavaScript focusout event
  • Traverse array object using JavaScript
  • JavaScript create and download CSV file
  • How to make beep sound in JavaScript
  • How to add a WhatsApp share button in a website using JavaScript
  • JavaScript Execution Context
  • JavaScript querySelector
  • Shallow Copy in JavaScript
  • How to Toggle Password Visibility in JavaScript
  • Removing Duplicate From Arrays
  • JavaScript insertBefore
  • JavaScript Select Option
  • Get and Set Scroll Position of an Element
  • Getting Child Elements of a Node in JavaScript
  • JavaScript scrollIntoView
  • JavaScript String startsWith
  • JS First Class Function
  • JavaScript Default Parameters
  • JavaScript Recursion in Real Life
  • JavaScript removeChild
  • Remove options from select list in JavaScript
  • JavaScript Calculator
  • Palindrome in JavaScript
  • JavaScript Call Stack
  • Fibonacci series in JavaScript
  • JavaScript appendchild() method
  • Ripple effect JavaScript
  • Convert object to array in Javascript
  • JavaScript Async/Await
  • JavaScript Blob
  • Check if the array is empty or null, or undefined in JavaScript
  • JavaScript Animation
  • JavaScript Design Patterns
  • JavaScript format numbers with commas
  • Currying in JavaScript
  • JavaScript hasOwnProperty
  • How to make a curved active tab in the navigation menu using HTML CSS and JavaScript
  • Http Cookies
  • JavaScript Comparison
  • JavaScript Confirm
  • JavaScript Garbage
  • JavaScript Special Characters
  • JavaScript Time Now
  • Lodash_.chain() Method
  • Underscore.js _.filter Function
  • JavaScript Factory Function
  • JavaScript for...in Loop
  • Window Location in JavaScript
  • JavaScript Certification Free
  • JavaScript MutationObserver function
  • Npm uninstall command
  • Npm Update Library and Npm List
  • Backend Project Ideas
  • How to become a Front-End Developer
  • Create a JavaScript Countdown Timer
  • Detect or Check Caps Lock Key is ON or OFF using JavaScript
  • How to Iterate through a JavaScript Object
  • JavaScript Fetch API
  • Javascript history.pushState() Method
  • JavaScript Infinity PROPERTY
  • JavaScript insertAdjacentHTML() method
  • How to use Console in JavaScript
  • Insert data into javascript indexedDB
  • JavaScript Exponentiation Operator
  • JavaScript indexedDB
  • Javascript offsetX property
  • Javascript offsetY property
  • JavaScript onunload Event
  • JAVASCRIPT TRIGGER CLICK
  • npm Install Command
  • How to check empty objects in JavaScript
  • How to Check the Specific Element in the JavaScript Class
  • JavaScript NaN Function
  • JavaScript onbeforeunload Event
  • Read Data from JavaScript IndexedDB
  • Delete data from javascript indexedDB
  • NextSibling Property in Javascript
  • PreviousSibling Property in Javascript
  • JavaScript sessionStorage
  • previousElementSibling Property in javascript
  • Base64 Decoding In JavaScript
  • How to get domain name from URL in JavaScript
  • Difference between preventDefault() and stopPropagation() methods
  • JavaScript padStart() Method
  • Javascript promise chaining
  • How to check two array values are equal in JavaScript
  • How to remove a Key/Property from an object in JavaScript
  • JavaScript Endswith() Function
  • How to draw a line using javascript
  • JavaScript windows getComputedStyle() Method
  • Difference between indexof and search in JavaScript
  • How to capitalize the first letter of string in JavaScript
  • How to sort characters in a string in JavaScript
  • How to pick random elements from an Array
  • How to Remove an Event Handler Using JavaScript Method
  • Javascript translate() method
  • GIF Player using CSS and JS
  • Javascript Async Generator function
  • Javascript "for...of" loop
  • JavaScript globalThis Object
  • JavaScript Logical Assignment Operators
  • JavaScript numerical separator
  • JavaScript prepend() method
  • Javascript regexp Lookahead
  • Javascript regexp Lookbehind
  • How to remove classes in javascript
  • JavaScript unary operators
  • Filterable Gallery Using Filterizr.js
  • Create Presentation using JavaScript Framework
  • Javascript Focus Method
  • JavaScript hashchange Event
  • The Oninput Function in Javascript
  • How to get parent element in Javascript
  • False Values in JavaScript
  • Callback Hell in JavaScript
  • How to Click Link Using JavaScript
  • JavaScript FormData
  • JavaScript onmousewheel event
  • JavaScript onkeyup Event
  • JavaScript string repeat() method
  • The textContent in Javascript
  • JavaScript Throttling
  • PolyFill JS
  • What is WebSocket
  • How to check if a variable is not NULL in JavaScript
  • Text to Particles Dissolve Effect JavaScript and CSS
  • How to use the mousedown event in javascript
  • How to use the mouseup event in javascript
  • The mousemove Event in JavaScript
  • How to create a dynamic table in JavaScript
  • How to remove class in JavaScript
  • Javascript Mouseenter and mouseleave event
  • JavaScript onwheel mouse event
  • Mouseout event in javascript
  • Mouseover function in javascript
  • Pressing and releasing the left mouse button in JavaScript
  • Remove All Whitespace from a String in JavaScript
  • Javascript getModifierState() KeyboardEvent Method
  • JavaScript only Number Regex
  • Javascript keyboard events
  • Lodash _.find() Method
  • Lodash_.get() Method
  • JavaScript MCQ

Interview Questions

  • JavaScript I/Q
  • JavaScript DataView
  • getFloat32()
  • getFloat64()
  • getUint16()
  • getUint32()

JavaScript Handler

  • JavaScript handler
  • construct()
  • defineProperty()
  • deleteProperty()
  • getOwnPropertyDescriptor()
  • getPrototypeOf()
  • isExtensible()
  • preventExtensions()
  • setPrototypeOf()

JavaScript JSON Object

  • JavaScript JSON
  • JSON.parse()
  • JSON.stringify()

JavaScript Number Methods

  • isInteger()
  • parseFloat()
  • toExponential()
  • toPrecision()
  • JavaScript Reflect
  • Reflect.apply()
  • Reflect.construct()
  • Reflect.defineProperty()
  • JavaScript Symbol
  • Symbol.for()
  • Symbol.keyFor()
  • Symbol.toString()

Symbol Property

  • Symbol.hasInstance
  • Symbol.isConcatSpreadable
  • Symbol.match
  • Symbol.prototype
  • Symbol.replace
  • Symbol.search
  • Symbol.split
  • Symbol.toStringTag
  • Symbol.unscopables

JavaScript Math Methods

  • Math abs() method
  • Math acos() method
  • Math asin() method
  • Math atan() method
  • Math cbrt() method
  • Math ceil() method
  • Math cos() method
  • Math cosh() method
  • Math exp() method
  • Math floor() method
  • Math hypot() method
  • Math log() method
  • Math max() method
  • Math min() method
  • Math pow() method
  • Math random() method
  • Math round() method
  • Math sign() method
  • Math sin() method
  • Math sinh() method
  • Math sqrt() method
  • Math tan() method
  • Math tanh() method
  • Math trunc() method

JavaScript Date Methods

  • getFullYears()
  • getMilliseconds()
  • getMinutes()
  • getSeconds()
  • getUTCDate()
  • getUTCDay()
  • getUTCFullYears()
  • getUTCHours()
  • getUTCMinutes()
  • getUTCMonth()
  • getUTCSeconds()
  • setMilliseconds()
  • setMinutes()
  • setSeconds()
  • setUTCDate()
  • setUTCFullYears()
  • setUTCHours()
  • setUTCMinutes()
  • setUTCMonth()
  • setUTCSeconds()
  • toDateString()
  • toISOString()
  • toTimeString()
  • toUTCString()

JavaScript Map Methods

  • Map clear() method
  • Map delete() method
  • Map entries() method
  • Map forEach() method
  • Map get() method
  • Map has() method
  • Map keys() method
  • Map set() method
  • Map values() method

JavaScript Object Methods

  • Object.assign() method
  • Object.create() method
  • Object.defineProperty() method
  • Object.defineProperties() method
  • Object.entries() method
  • Object.freeze() method
  • getOwnPropertyDescriptor() method
  • getOwnPropertyDescriptors() method
  • getOwnPropertyNames() method
  • getOwnPropertySymbols() method
  • Object.getPrototypeOf() method
  • Object.is() method
  • preventExtensions() method
  • Object.seal() method
  • Object.setPrototypeOf() method
  • Object.values() method

JavaScript Set Methods

  • Set add() method
  • Set clear() method
  • Set delete() method
  • Set entries() method
  • Set forEach() method
  • Set has() method
  • Set values() method

JavaScript String Methods

  • charCodeAt()
  • lastIndexOf()
  • substring()
  • toLowerCase()
  • toLocaleLowerCase()
  • toUpperCase()
  • toLocaleUpperCase()

JavaScript TypedArray Method

  • copyWithin()
  • findIndex()
  • lastIndexof()
  • reduceRight()
  • toLocaleString()

JavaScript WeakMap Methods

Javascript weakset methods.

Javascript logical assignment operators help to use the logical operators with the default and another expression. It works between two expressions or values with a single operator. ES2021 provides three logical assignment operators, which are as follows:

The following table displays the difference between the basic and logical assignment operators.

ES Logical Assignment OperatorsBasic Logical Operators
a &&= ba && (a = b)
a ||= ba || (a = b)
a ??= ba ?? (a = b);

Logical AND assignment operator (&&=)

The &&= symbol is a "Logical AND assignment operator" and connects two variables. If the initial value is correct, the second value is used. It is graded from left to right.

The following syntax shows the Logical AND assignment operator with the two values.

The examples work with multiple values using the "Logical AND assignment operator" in the javascript.

The following example shows basic values for the "AND assignment operator" in javascript.

The image shows the "logical AND assignment operator's data" as an output.

JavaScript Logical Assignment Operators

The following example shows the "AND assignment operator" hash in javascript.

The image shows the "logical and assignment operator's data" as an output.

JavaScript Logical Assignment Operators

The following example shows an array for the "AND assignment operator" in javascript.

JavaScript Logical Assignment Operators

Logical OR assignment operator (||=)

The ||= is a "logical OR assignment operator" between two values. If the initial value is incorrect, the second value is used. It is graded from left to right.

The following syntax shows the Logical OR assignment operator with the two values.

The examples work with multiple values using the " Logical OR assignment operator" in the javascript.

The following example shows basic values for the "Logical OR assignment" in javascript. Here, We can use simple numeric values.

The image shows the "logical OR assignment operator's data" as an output.

JavaScript Logical Assignment Operators

The following example shows the "OR assignment operator" hash in javascript.

The image shows the " Logical OR assignment operator's data" as an output.

JavaScript Logical Assignment Operators

The following example shows arrays for the "OR assignment operator" in javascript.

JavaScript Logical Assignment Operators

Nullish coalescing assignment operator (??=)

The ??= is a "Nullish coalescing assignment operator" between two values. The second value is assigned if the first value is undefined or null. It is graded from left to right.

The following syntax shows the Logical nullish assignment operator with the two values.

The examples work with multiple values using the " Logical nullish assignment operator" in the javascript.

The following example shows basic values for the "Logical nullish assignment" in javascript. Here, We can use simple numeric values.

The image shows the "logical nullish assignment operator's data" as an output.

JavaScript Logical Assignment Operators

The following example shows hash values for the "Logical nullish assignment" in javascript.

JavaScript Logical Assignment Operators

The following example shows array values for the "Logical nullish assignment" in javascript. The nullish operator uses the null and the "jtp" value to show functionality.

JavaScript Logical Assignment Operators

The javascript logical assignment operators help to operate logical conditions between two inputs in all data formats. The "and", "or", and nullish logical operation works by these operators in the javascript language.

Latest Courses

Python

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks

Contact info

G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India

[email protected] .

Facebook

Online Compiler

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

JavaScript Assignment Operators

A ssignment operators.

Assignment operators are used to assign values to variables in JavaScript.

Assignment Operators List

There are so many assignment operators as shown in the table with the description.

OPERATOR NAMESHORTHAND OPERATORMEANING
a+=ba=a+b
a-=ba=a-b
a*=ba=a*b
a/=ba=a/b
a%=ba=a%b
a**=ba=a**b
a<<=ba=a<<b
a>>=ba=a>>b
a&=ba=a&b
a|=ba=a | b
a^=ba=a^b

a&&=b

x && (x = y)

||=

x || (x = y)

??=

x ?? (x = y)

Below we have described each operator with an example code:

Addition assignment operator(+=).

The Addition assignment operator adds the value to the right operand to a variable and assigns the result to the variable. Addition or concatenation is possible. In case of concatenation then we use the string as an operand.

Subtraction Assignment Operator(-=)

The Substraction Assignment Operator subtracts the value of the right operand from a variable and assigns the result to the variable.

Multiplication Assignment Operator(*=)

The Multiplication Assignment operator multiplies a variable by the value of the right operand and assigns the result to the variable.

Division Assignment Operator(/=)

The Division Assignment operator divides a variable by the value of the right operand and assigns the result to the variable.

Remainder Assignment Operator(%=)

The Remainder Assignment Operator divides a variable by the value of the right operand and assigns the remainder to the variable.

Exponentiation Assignment Operator

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

Left Shift Assignment Operator(<<=)

This Left Shift Assignment O perator moves the specified amount of bits to the left and assigns the result to the variable.

Right Shift Assignment O perator(>>=)

The Right Shift Assignment Operator moves the specified amount of bits to the right and assigns the result to the variable.

Bitwise AND Assignment Operator(&=)

The Bitwise AND Assignment Operator uses the binary representation of both operands, does a bitwise AND operation on them, and assigns the result to the variable.

Btwise OR Assignment Operator(|=)

The Btwise OR Assignment Operator uses the binary representation of both operands, does a bitwise OR operation on them, and assigns the result to the variable.

Bitwise XOR Assignment Operator(^=)

The Bitwise XOR Assignment Operator uses the binary representation of both operands, does a bitwise XOR operation on them, and assigns the result to the variable.

Logical AND Assignment Operator(&&=)

The Logical AND Assignment assigns the value of  y  into  x  only if  x  is a  truthy  value.

Logical OR Assignment Operator( ||= )

The Logical OR Assignment Operator is used to assign the value of y to x if the value of x is falsy.

Nullish coalescing Assignment Operator(??=)

The Nullish coalescing Assignment Operator assigns the value of y to x if the value of x is null.

Supported Browsers: The browsers supported by all JavaScript Assignment operators are listed below:

  • Google Chrome
  • Microsoft Edge

JavaScript Assignment Operators – FAQs

What are assignment operators in javascript.

Assignment operators in JavaScript are used to assign values to variables. The most common assignment operator is the equals sign (=), but there are several other assignment operators that perform an operation and assign the result to a variable in a single step.

What is the basic assignment operator?

The basic assignment operator is =. It assigns the value on the right to the variable on the left.

What are compound assignment operators?

Compound assignment operators combine a basic arithmetic or bitwise operation with assignment. For example, += combines addition and assignment.

What does the += operator do?

The += operator adds the value on the right to the variable on the left and then assigns the result to the variable.

How does the *= operator work?

The *= operator multiplies the variable by the value on the right and assigns the result to the variable.

Can you use assignment operators with strings?

Yes, you can use the += operator to concatenate strings.

What is the difference between = and ==?

The = operator is the assignment operator, used to assign a value to a variable. The == operator is the equality operator, used to compare two values for equality, performing type conversion if necessary.

What does the **= operator do?

The **= operator performs exponentiation (raising to a power) and assigns the result to the variable.

Please Login to comment...

Similar reads.

  • Web Technologies
  • javascript-operators
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
  • #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?

JS Reference

Html events, html objects, other references, javascript operators reference, javascript operators.

Operators are used to assign values, compare values, perform arithmetic operations, and more.

There are different types of JavaScript operators:

  • Arithmetic Operators
  • Assignment Operators

Comparison Operators

Logical operators.

  • Conditional Operators
  • Type Operators

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y = 5 , the table below explains the arithmetic operators:

Oper Name Example Results Try it
+ Addition x = y + 2 y=5, x=7
- Subtraction x=y-2 y=5, x=3
* Multiplication x=y*2 y=5, x=10
** Exponentiation
x=y**2 y=5, x=25
/ Division x = y / 2 y=5, x=2.5
% Remainder x = y % 2 y=5, x=1
++ Pre increment x = ++y y=6, x=6
++ Post increment x = y++ y=6, x=5
-- Pre decrement x = --y y=4, x=4
-- Post decrement x = y-- y=4, x=5

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

Given that x = 10 and y = 5 , the table below explains the assignment operators:

Oper Example Same As Result Try it
= x = y x = y x = 5
+= x += y x = x + y x = 15
-= x -= y x = x - y x = 5
*= x *= y x = x * y x = 50
/= x /= y x = x / y x = 2
%= x %= y x = x % y x = 0
: x: 45 size.x = 45 x = 45

Advertisement

JavaScript String Operators

The + operator, and the += operator can also be used to concatenate (add) strings.

Given that t1 = "Good " , t2 = "Morning" , and t3 = "" , the table below explains the operators:

Oper Example t1 t2 t3 Try it
+ t3 = t1 + t2 "Good " "Morning"  "Good Morning"
+= t1 += t2 "Good Morning" "Morning"

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

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

Oper Name Comparing Returns Try it
== equal to x == 8 false
== equal to x == 5 true
=== equal value and type x === "5" false
=== equal value and type x === 5 true
!= not equal x != 8 true
!== not equal value or type x !== "5" true
!== not equal value or type x !== 5 false
> greater than x > 8 false
< less than x < 8 true
>= greater or equal to x >= 8 false
<= less or equal to x <= 8

Conditional (Ternary) Operator

The conditional operator assigns a value to a variable based on a condition.

Syntax Example Try it
(condition) ? x : y (z < 18) ? x : y

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

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

Oper Name Example Try it
&& AND (x < 10 && y > 1) is true
|| OR (x === 5 || y === 5) is false
! NOT !(x === y) is true

The Nullish Coalescing Operator (??)

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

Otherwise it returns the second argument.

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

Chrome 80 Edge 80 Firefox 72 Safari 13.1 Opera 67
Feb 2020 Feb 2020 Jan 2020 Mar 2020 Mar 2020

The Optional Chaining Operator (?.)

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

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

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers. Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number.

Oper Name Example Same as Result Decimal Try it
& AND x = 5 & 1 0101 & 0001 0001 1
| OR x = 5 | 1 0101 | 0001 0101 5
~ NOT x = ~ 5 ~0101 1010 10
^ XOR x = 5 ^ 1 0101 ^ 0001 0100 4
<< Left shift x = 5 << 1 0101 << 1 1010 10
>> Right shift x = 5 >> 1 0101 >> 1 0010 2
>>> Unsigned right x = 5 >>> 1 0101 >>> 1 0010 2

The table above uses 4 bits unsigned number. Since JavaScript uses 32-bit signed numbers, ~ 5 will not return 10. It will return -6. ~00000000000000000000000000000101 (~5) will return 11111111111111111111111111111010 (-6)

The typeof Operator

The typeof operator returns the type of a variable, object, function or expression:

Please observe:

  • The data type of NaN is number
  • The data type of an array is object
  • The data type of a date is object
  • The data type of null is object
  • The data type of an undefined variable is undefined

You cannot use typeof to define if a JavaScript object is an array or a date.

Both array and date return object as type.

The delete Operator

The delete operator deletes a property from an object:

The delete operator deletes both the value of the property and the property itself.

After deletion, the property cannot be used before it is added back again.

The delete operator is designed to be used on object properties. It has no effect on variables or functions.

The delete operator should not be used on the properties of any predefined JavaScript objects (Array, Boolean, Date, Function, Math, Number, RegExp, and String).

This can crash your application.

The Spread (...) Operator

The ... operator can be used to expand an iterable into more arguments for function calls:

The in Operator

The in operator returns true if a property is in an object, otherwise false:

Object Example

You cannot use in to check for array content like ("Volvo" in cars).

Array properties can only be index (0,1,2,3...) and length.

See the examples below.

Predefined Objects

The instanceof operator.

The instanceof operator returns true if an object is an instance of a specified object:

The void Operator

The void operator evaluates an expression and returns undefined . This operator is often used to obtain the undefined primitive value, using "void(0)" (useful when evaluating an expression without using the return value).

JavaScript Operator Precedence

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.

Javascript AND operator within assignment

I know that in JavaScript you can do:

where the variable oneOrTheOther will take on the value of the first expression if it is not null , undefined , or false . In which case it gets assigned to the value of the second statement.

However, what does the variable oneOrTheOther get assigned to when we use the logical AND operator?

What would happen when someOtherVar is non-false? What would happen when someOtherVar is false?

Just learning JavaScript and I'm curious as to what would happen with assignment in conjunction with the AND operator.

  • variable-assignment
  • logical-operators
  • and-operator

Bergi's user avatar

  • 3 Try it. jsfiddle.net/uv6LR –  icktoofay Commented Jul 2, 2010 at 5:30
  • 1 see my answer from a related post.. stackoverflow.com/questions/3088098/… –  Anurag Commented Jul 2, 2010 at 5:59
  • In your example, if someOtherVar is undefined it will throw an error. Using window.someOtherVar will allow it to take on the second value if it someOtherVar is undefined. –  Rich Commented May 13, 2015 at 0:11

7 Answers 7

Basically, the Logical AND operator ( && ), will return the value of the second operand if the first is truthy , and it will return the value of the first operand if it is by itself falsy , for example:

Note that falsy values are those that coerce to false when used in boolean context, they are null , undefined , 0 , NaN , an empty string, and of course false , anything else coerces to true .

Christian C. Salvadó's user avatar

  • Ah ok. Thanks. That makes sense as, after all, it's the reverse of the OR operator. –  Alex Commented Jul 2, 2010 at 5:29
  • Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false. ( developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… ) –  Bardelman Commented Oct 22, 2015 at 11:00
  • I love the example. It would be great if you'd include a bit about && being called a 'guard' operator that's good for null checks as that's good context to have. You could even cite Douglas Crockford here: javascript.crockford.com/survey.html –  Akrikos Commented Apr 21, 2016 at 14:02

&& is sometimes called a guard operator.

it can be used to set the value only if the indicator is truthy.

mykhal's user avatar

  • 3 Really clear answer. The other answers left me rather baffled, but this is a very clear way of expressing it. Thank you! –  ctaymor Commented Jul 23, 2014 at 20:18
  • I think this answer is clearly wrong. After the above statement has been executed the value of 'variable' is the value of the expression "indicator && value" whatever that may be. So the value of the variable on the left side of the assignment is set always to something. regardless of what happens on the right side (unless an error is thrown). No? –  Panu Logic Commented Dec 29, 2020 at 21:46

Beginners Example

If you are trying to access "user.name" but then this happens:

Fear not. You can use ES6 optional chaining on modern browsers today.

See MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Here's some deeper explanations on guard operators that may prove useful in understanding.

Before optional chaining was introduced, you would solve this using the && operator in an assignment or often called the guard operator since it "guards" from the undefined error happening.

Here are some examples you may find odd but keep reading as it is explained later.

Explanation : In the guard operation, each term is evaluated left-to-right one at a time . If a value evaluated is falsy, evaluation stops and that value is then assigned. If the last item is reached, it is then assigned whether or not it is falsy.

falsy means it is any one of these values undefined, false, 0, null, NaN, '' and truthy just means NOT falsy.

Bonus: The OR Operator

The other useful strange assignment that is in practical use is the OR operator which is typically used for plugins like so:

which will only assign the code portion if "this.myWidget" is falsy. This is handy because you can declare code anywhere and multiple times not caring if its been assigned or not previously, knowing it will only be assigned once since people using a plugin might accidentally declare your script tag src multiple times.

Explanation : Each value is evaluated from left-to-right, one at a time . If a value is truthy, it stops evaluation and assigns that value, otherwise, keeps going, if the last item is reached, it is assigned regardless if it is falsy or not.

Extra Credit: Combining && and || in an assignment

You now have ultimate power and can do very strange things such as this very odd example of using it in a palindrome.

In depth explanation here: Palindrome check in Javascript

Happy coding.

King Friday's user avatar

  • thank you, awesome example! Help me a lot to understand && and || operators! +1 –  Lucky Commented Jul 17, 2015 at 19:27
  • Thank you for this answer! I'm curious how long will JS keep trying to access the deepest level property? For example, if you were waiting for a response to hit your backend, is it safe to use var x = y && y.z ? –  Scott Savarie Commented Jan 8, 2018 at 8:29

Quoting Douglas Crockford 1 :

The && operator produces the value of its first operand if the first operand is falsy. Otherwise it produces the value of the second operand.

1 Douglas Crockford: JavaScript: The Good Parts - Page 16

Daniel Vassallo's user avatar

  • Crockford also calls it the 'guard operator' here: javascript.crockford.com/survey.html –  Akrikos Commented Apr 21, 2016 at 14:00

According to Annotated ECMAScript 5.1 section 11.11 :

In case of the Logical OR operator(||),

expr1 || expr2 Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

In the given example,

var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...move along";

The result would be the value of someOtherVar, if Boolean(someOtherVar) is true .(Please refer. Truthiness of an expression ). If it is false the result would be "these are not the droids you are looking for...move along";

And In case of the Logical AND operator(&&),

Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

case 1: when Boolean(someOtherVar) is false: it returns the value of someOtherVar.

case 2: when Boolean(someOtherVar) is true: it returns "these are not the droids you are looking for...move along".

BatScream's user avatar

I see this differently then most answers, so I hope this helps someone.

To calculate an expression involving || , you can stop evaluating the expression as soon as you find a term that is truthy. In that case, you have two pieces of knowledge, not just one:

  • Given the term that is truthy, the whole expression evaluates to true.
  • Knowing 1, you can terminate the evaluation and return the last evaluated term.

For instance, false || 5 || "hello" evaluates up until and including 5, which is truthy, so this expression evaluates to true and returns 5.

So the expression's value is what's used for an if-statement, but the last evaluated term is what is returned when assigning a variable.

Similarly, evaluating an expression with && involves terminating at the first term which is falsy. It then yields a value of false and it returns the last term which was evaluated. (Edit: actually, it returns the last evaluated term which wasn't falsy. If there are none of those, it returns the first.)

If you now read all examples in the above answers, everything makes perfect sense :)

(This is just my view on the matter, and my guess as to how this actually works. But it's unverified.)

Ted van Gageldonk's user avatar

I have been seeing && overused here at work for assignment statements. The concern is twofold: 1) The 'indicator' check is sometimes a function with overhead that developers don't account for. 2) It is easy for devs to just see it as a safety check and not consider they are assigning false to their var. I like them to have a type-safe attitude, so I have them change this:

var currentIndex = App.instance && App.instance.rightSideView.getFocusItemIndex();

var currentIndex = App.instance && App.instance.rightSideView.getFocusItemIndex() || 0;

so they get an integer as expected.

Drew Deal'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 variable-assignment logical-operators and-operator or ask your own question .

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

Hot Network Questions

  • Stuck as a solo dev
  • How many engineers/scientists believed that human flight was imminent as of the late 19th/early 20th century?
  • Looking for a short story on chess, maybe published in Playboy decades ago?
  • Custom PCB with Esp32-S3 isn't recognised by Device Manager for every board ordered
  • Why is resonance such a widespread phenomenon?
  • Longtable goes beyond the right margin and footnote does not fit under the table
  • How can I analyze the anatomy of a humanoid species to create sounds for their language?
  • mmrm R package : No optimizer led to a successful model fit
  • What unintended side effects may arise from making bards count as both arcane and divine spellcasters?
  • What are the pros and cons of the classic portfolio by Wealthfront?
  • How to prevent a bash script from running repeatedly at the start of the terminal
  • How did people know that the war against the mimics was over?
  • Why did early ASCII have ← and ↑ but not ↓ or →?
  • Why is the \[ThickSpace] character defined as 5/18 em instead of 1/4 em as in Unicode?
  • Why do I often see bunches of medical helicopters hovering in clusters in various locations
  • Do carbon fiber wings need a wing spar?
  • Movie where a young director's student film gets made (badly) by a major studio
  • What’s the name of this horror movie where a girl dies and comes back to life evil?
  • How did NASA figure out when and where the Apollo capsule would touch down on the ocean?
  • How do elected politicians get away with not giving straight answers?
  • Can landlords require HVAC maintenance in New Mexico?
  • Negating a multiply quantified statement
  • Multi-producer, multi-consumer blocking queue
  • Is it really a "space walk" (EVA proper) if you don't get your feet wet (in space)?

logical assignment operator in javascript

IMAGES

  1. The new Logical Assignment Operators in JavaScript

    logical assignment operator in javascript

  2. JavaScript Logical Assignment Operators

    logical assignment operator in javascript

  3. JavaScript Logical Assignment Operators

    logical assignment operator in javascript

  4. Understanding JavaScript Operators With Types and Examples

    logical assignment operator in javascript

  5. JavaScript Operators.

    logical assignment operator in javascript

  6. JavaScript Logical Assignment Operators

    logical assignment operator in javascript

VIDEO

  1. Operators in JavaScript

  2. Java Script Logical Operator Lesson # 08

  3. Section 3 Operators Part 2 UNIT-4: INTRODUCTION TO DYNAMIC WEBSITES USING JAVASCRIPT 803

  4. Logical Operator in JavaScript

  5. JavaScript Arithmetic Operators

  6. Operators Part2 and Array Part1

COMMENTS

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

  2. JavaScript Logical Assignment Operators

    The logical OR assignment operator (||=) accepts two operands and assigns the right operand to the left operand if the left operand is falsy: In this syntax, the ||= operator only assigns y to x if x is falsy. For example: console.log(title); Code language: JavaScript (javascript) Output: In this example, the title variable is undefined ...

  3. JavaScript Assignment

    JavaScript Assignment Operators. Assignment operators assign values to JavaScript variables. Operator Example Same As = x = y: x = y += x += y: x = x + y-= x -= y: x = x - y *= ... The Logical OR assignment operator is used between two values. If the first value is false, the second value is assigned.

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

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

  6. Logical OR assignment (||=)

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

  7. Logical operators

    The "OR" operator is represented with two vertical line symbols: result = a || b; In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are true, it returns true, otherwise it returns false. In JavaScript, the operator is a little bit trickier and more powerful.

  8. JavaScript Logical AND assignment (&&=) Operator

    JavaScript Logical AND assignment (&&=) Operator. This operator is represented by x &&= y, and it is called the logical AND assignment operator. It assigns the value of y into x only if x is a truthy value. We use this operator x &&= y like this. Now break this expression into two parts, x && (x = y). If the value of x is true, then the ...

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

  10. Learn JavaScript Operators

    The second group of operators we're going to explore is the assignment operators. Assignment operators are used to assign a specific value to a variable. The basic assignment operator is marked by the equal = symbol, and you've already seen this operator in action before: let x = 5; After the basic assignment operator, there are 5 more ...

  11. JavaScript Logical Assignment Operators

    Javascript logical assignment operators help to use the logical operators with the default and another expression. It works between two expressions or values with a single operator. ES2021 provides three logical assignment operators, which are as follows: Logical AND assignment operator. Logical OR assignment operator.

  12. JavaScript Logical Operators

    Logical operators in JavaScript are used for making decisions based on conditions and manipulating boolean values. They are commonly used to compare variables or values and set termination conditions for loops. In JavaScript, there are basically three types of logical operators. OPERATOR NAME. OPERATOR SYMBOL.

  13. Logical OR (||)

    The logical OR (||) (logical disjunction) operator for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value. However, the || operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value.

  14. JavaScript Assignment Operators

    This operator is represented by x &amp;&amp;= y, and it is called the logical AND assignment operator. It assigns the value of y into x only if x is a truthy value. We use this operator x &amp;&amp;= y like this. Now break this expression into two parts, x &amp;&amp; (x = y). If the value of x is true, then the statement (x = y) executes, and the v

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

  16. JavaScript Operators Reference

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

  17. Logical AND assignment (&&=)

    The logical AND assignment (&&=) operator only evaluates the right operand and assigns to the left if the left operand is truthy. Logical AND 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 truthy, due to ...

  18. Logical Assignment Operators in Modern JavaScript

    Advantages of Logical Assignment Operators. Readability: By combining logic and assignment into a single operator, code can become more concise and easier to read at a glance. Efficiency: These operators potentially reduce the number of operations the JavaScript engine has to execute, leading to minor performance improvements in some scenarios.

  19. Expressions and operators

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

  20. Javascript AND operator within assignment

    Basically, the Logical AND operator (&&), will return the value of the second operand if the first is truthy, and it will return the value of the first operand if it is by itself falsy, for example:true && "foo"; // "foo" NaN && "anything"; // NaN 0 && "anything"; // 0 Note that falsy values are those that coerce to false when used in boolean context, they are null, undefined, 0, NaN, an empty ...