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:

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:

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.

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

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

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

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.

Assignment operators are fully described in the JS Assignment chapter.

JavaScript Comparison Operators

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

Logical operators are fully described in the JS Comparisons chapter.

JavaScript Type Operators

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

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

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.

DEV Community

DEV Community

tywenk

Posted on Apr 12, 2022

Javascript Shorthands: Ternary, Logical || and && Assignments

Gotta go fast.

Why waste time say lot word when few word do trick?

This is perhaps the insidious mantra of programmers the world over. Too busy hacking into the mainframe they have no time for multisyllabic variable names. They don't have the bandwidth in their own minds to cache long winded expressions. They would rather use --nay, they NEED to use-- terse, to-the-point, language to snipe their bits out of the sky. Like a painter at an easel, a programmer at a greasy keyboard feels the gravitational pull, the irresistible urge, the hypnotic Siren's song... to use shorthand expressions .

Wise programmers often warn young programmers to not adopt this mentality, especially while learning how to code. It can become a bad habit that can in cases lead to harder to read, harder to maintain, and harder to update code. That said, in my explorations of the topic, I found it useful to discover (to my delight) that a) there are proper places to use it, and b) people do use them and you should know how to read them. This blog is about the ternary expression and its tangent cousins -- the AND and the OR operators -- and how they can be used to write succinct yet still straightforward code.

The Ternary Expression

Ternary expressions are a shorthand way to write if else statements.

Ternary expressions threw me off early on. The semantic structure of if else statement was easy to understand. If this expression returns truthy, then execute this expression. If it is not truthy, execute this other expression. Why fix something that ain't broke?

The strange syntax of a ? and the trailing : were confusing. I think it's because when reading a line of code, the ? and : can be easily lost in the jumble of text and numbers.

Here's a breakdown of it, in plain English:

if this is true ? then do this : otherwise do this

The usefulness of ternary expressions comes in handy when you want a single-line way to assign a variable a value dependent on another variable. Let's take these three lines that return a isFullyCharged as true if our battery level is at 100%.

Written out as an if else statement, and assuming we still want to return a new boolean variable, it comes out much longer.

Ternary expressions are useful then for concise single-line checks that are actually quite readable once their at first strange syntax can be overcome.

And, as I've read more about them, they can also simplify more complex situations, like nested checks, in which case using chained ternary expressions results in cleaner and less bug prone code.

The Logical OR Assignment

The logical OR operator can be used in many ways, but the one I will discuss here is its use as a way to check a value before assignment to a variable.

The OR operator, denoted as || , can be used in the primary statement to return a true or false value.

The || operator typically takes two expressions on either side of it. Take this example:

This short program returns a true or false boolean. The OR operator is executed left to right. First b > a is checked to be true. In this case, b is smaller than a , so the expression returns false . Upon this return the || operator then returns the value of the expression on its right. In this case, a > b returns true, because 5 is a larger number than 1, so as a result the entire expression returns true.

When it comes to logical OR assignment can be used as a checker to ensure a value is empty before assigning it. For instance, this example:

The ||= operator only assigns name to "No name" if name is falsy.

The output of this program will be "No name". The ||= shorthand is a way to check if the value on the left is falsy before assigning it to the value on the right. In this case, name is declared but undefined, so has the value undefined . In Javascript, undefined is considered a falsy value, so as an primitive value it returns false . Because the left expression is false, the right expression is executed.

This might become more clear if the name ||= "No name" expression is pulled apart, into its non-shorthand components. That expression is equivalent to name || (name = "No name") !

This is worth reiterating, the following two expressions are equivalent, and both assign "No name" to name :

This is easier to read, as it more closely resembles the typical OR expression. In essence, this shorthand is a quick way to check if the value of name is falsy before deciding to assign it a value. This can be useful when you don't want to overwrite a variable or if you don't want to return undefined and only return a legible string instead.

Using the ||= is also completely different from assigning a variable to an OR expression. For instance, name = "No name" || "Other name is valid, and will assign name to "No name" , but it does so through a different means than the ||=

The Logical AND Assignment

The logical AND is much like the OR. Instead denoted as && , it is also an operator that takes in two values, one of the left and one on the right. In this case, both the left and right values must convert into truthy values for the second value to be returned. Otherwise the first value is returned. This evaluation is executed left to right. If the left value converts to falsy, the right value is never evaluated and the entire AND expression returns false. However if both execute as truthy, then the second value will be returned.

So take the example:

In the first expression, '' is an empty string and considered falsy. The entire && expression then returns the first value, which is falsely, and short circuits the entire expression. In the second expression, name is assigned to 'Jill' because both strings 'Bob' and 'Jill' return truthy, and so both are evaluated. Because both evaluate true, the second value is returned.

Now we go onto the logical AND assignment :

When it comes to the logical AND assignment, denoted by &&= , the expression only assigns name to "Tywen" if name is truthy. name is actually falsy, as it is undefined, so name is not assigned the value "Tywen" . lastname on the other hand is assigned a truthy value of "Exists" , so when it comes time to assign it with a logical AND assignment, it successfully assigns it to "Kelly" .

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

coderoflagos profile image

Things I wish I knew before I started an open-source project

Opemipo Disu - May 23

n968941 profile image

Nvidia's Potential Entry into ARM-based Laptops

Nilesh Payghan - May 23

makoto0825 profile image

How to use Promise chaining in Javascript.

Makoto Tsuga - May 23

codewithcaen profile image

Make your sites more accessible by setting max icon widths

CodeWithCaen - May 23

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

  • Skip to main content

UDN Web Docs: MDN Backup

  • Logical AND assignment (&&=)

The logical AND assignment ( x &&= y ) operator only assigns if x is truthy .

Description

Short-circuit evaluation.

The logical AND operator is evaluated left to right, it is tested for possible short-circuit evaluation using the following rule:

(some falsy expression) && expr is short-circuit evaluated to the falsy expression;

Short circuit means that the expr part above is not evaluated , hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place).

Logical AND assignment short-circuits as well meaning that x &&= y is equivalent to:

And not equivalent to the following which would always perform an assignment:

Using logical AND assignment

Specifications, browser compatibility.

  • Logical AND (&&)
  • The nullish coalescing operator ( ?? )
  • Bitwise AND assignment ( &= )
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Using promises
  • Iterators and generators
  • Meta programming
  • JavaScript modules
  • Client-side JavaScript frameworks
  • Client-side web APIs
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • AggregateError
  • ArrayBuffer
  • AsyncFunction
  • BigInt64Array
  • BigUint64Array
  • FinalizationRegistry
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • ReferenceError
  • SharedArrayBuffer
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Addition (+)
  • Addition assignment (+=)
  • Assignment (=)
  • Bitwise AND (&)
  • Bitwise AND assignment (&=)
  • Bitwise NOT (~)
  • Bitwise OR (|)
  • Bitwise OR assignment (|=)
  • Bitwise XOR (^)
  • Bitwise XOR assignment (^=)
  • Comma operator (,)
  • Conditional (ternary) operator
  • Decrement (--)
  • Destructuring assignment
  • Division (/)
  • Division assignment (/=)
  • Equality (==)
  • Exponentiation (**)
  • Exponentiation assignment (**=)
  • Function expression
  • Greater than (>)
  • Greater than or equal (>=)
  • Grouping operator ( )
  • Increment (++)
  • Inequality (!=)
  • Left shift (<<)
  • Left shift assignment (<<=)
  • Less than (<)
  • Less than or equal (<=)
  • Logical NOT (!)
  • Logical OR (||)
  • Logical OR assignment (||=)
  • Logical nullish assignment (??=)
  • Multiplication (*)
  • Multiplication assignment (*=)
  • Nullish coalescing operator (??)
  • Object initializer
  • Operator precedence
  • Optional chaining (?.)
  • Pipeline operator (|>)
  • Property accessors
  • Remainder (%)
  • Remainder assignment (%=)
  • Right shift (>>)
  • Right shift assignment (>>=)
  • Spread syntax (...)
  • Strict equality (===)
  • Strict inequality (!==)
  • Subtraction (-)
  • Subtraction assignment (-=)
  • Unary negation (-)
  • Unary plus (+)
  • Unsigned right shift (>>>)
  • Unsigned right shift assignment (>>>=)
  • async function expression
  • class expression
  • delete operator
  • function* expression
  • in operator
  • new operator
  • void operator
  • async function
  • for await...of
  • function declaration
  • import.meta
  • try...catch
  • Arrow function expressions
  • Default parameters
  • Method definitions
  • Rest parameters
  • The arguments object
  • Private class fields
  • Public class fields
  • constructor
  • Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: can't access lexical declaration "x" before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the "delete" operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: "x" is not iterable
  • TypeError: More arguments needed
  • TypeError: Reduce of empty array with no initial value
  • TypeError: X.prototype.y called on incompatible type
  • TypeError: can't access dead object
  • TypeError: can't access property "x" of "y"
  • TypeError: can't assign to property "x" on "y": not an object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cannot use "in" operator to search for "x" in "y"
  • TypeError: cyclic object value
  • TypeError: invalid "instanceof" operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features

JavaScript: Logical Operators

So we've already come quite a way with 'if' statements - but there are three more operators which can come in useful to make conditions and logic paths even more complex. These are called logical operators and are what we're going to be talking about in this tutorial.

The 'and' operator (expressed in JavaScript with a double ampersand - && ) is used to check if one expression and another is true. Both must be true for the condition to be true (and if used in an 'if statement', for the code to be executed).

We can use the 'and' operator in a very basic manor by writing one condition (using two values and a conditional operator), then using the 'and' operator ( && ), and then simply writing the second condition. Take the following for example:

So maybe we haven't created an extremely useful example to demonstrate the 'and' operator above, however this does illustrate some functionality which would be messy and difficult to achieve otherwise. We are checking if one condition and another are true.

The 'or' operator functions almost exactly like 'and', but instead of checking of the first and second expressions are true, it checks if either the first condition is true or the second condition is true (who would have guessed it, eh?). We can express the 'or' operator in JavaScript using a double "pipe symbol" ( || ) - this is often on keyboards to the left of 'Shift', or to the right of 'Enter'.

It's worth noting that the 'or' operator is not exclusive (it's not like XOR if you know about logical operators in general), so this means that it will also return 'true' if both the expressions it is evaluating are true. So let's write another abstract example!

'Or' can also be used to accept responses in varying cases within basic scripts, for example:

Now finally, the 'not' operator. This one is a little bit different to 'and' and 'or' - instead of being about joining conditions, it simply inverts them. So if a condition is true, putting the 'not' operator before it will make it false (and if you put the 'not' operator before a condition that is true, it will make it false).

You can write 'not' in JavaScript as you do in " not equal to" - by using an exclamation mark ( ! ). So if we wanted an 'if' statement to always be false, and wanted to use the 'not' operator to do it for some obscure reason - then we could write '!true' (or just 'false' which makes a lot more sense). So it's time to create an abstract example:

Notice how I bracketed up the whole condition I wanted to inverse (in the above case - checking if the users input was above 9000 or below -9000) and then simply put a '!' in-front of it to invert it. This condition is possible to formulate without using 'not', however the 'not' operator makes the code neater and more readable. 'Not' also has some clear uses outside of conditions - such as setting a variable to the inverse of another:

In the above case, variableTwo would be true (because it's '!false').

Playing around with different logical operators can help you get to grips with them and as always, I recommend either tweaking with the files in your project folder or playing around on JSFiddle .

Double && (and) Double || (or) = Double Functionality

Jeremy Robertson

Social Share Links

The and (&&) and or (||) operators in javascript do not function like traditional logical operators. We can use them to our advantage to eliminate some boilerplate code when writing conditional expressions.

Additional jsbin: https://jsbin.com/qipina/edit?js,output

[00:00] The double ampersand and double pipe are logical operators in JavaScript, but we can do some pretty cool shorthand conditional operations with them.

"[00:11] What's more fun -- Programming or Testing? Testing or Programming?" If I asked you if those two questions would have the same result, one would typically say yes, but in JavaScript, they will have two different answers because the order in which you ask the question has an impact.

[00:29] I'm asking one of the questions here, "Testing or Programming?" Right now, we're seeing that the result is "Testing," but if we were to change the order in which the question is asked, our result is going to change, even though we were using the same values to ask the question.

[00:48] The OR operator in JavaScript is checking if the value on the left-hand side is truthy. If it is, it returns the value from the left-hand side instead of simply giving you a Boolean equal to true.

[01:02] That means we're getting the entire programming object that we declared up here set as our result. Later, down here, in our render function, when we're accessing that result, we can pull the name property off of the programming object.

[01:17] Let's look at what happens if we put non-truthy values in here, like null or undefined. In both cases, we saw that our output updated to show "Testing." With the OR operator, if the left-hand side is undefined, it will return the entire value of the right-hand side.

[01:39] The AND operator is similar in that it can return one of the values being compared instead of a Boolean type. The differences are that it can only return the value on the right-hand side of the comparison and only if both the left and right-hand sides are truthy values.

[01:58] If we change this to null, we have no output because the left-hand side was not truthy, but when the value of both sides is truthy, we're getting the value of the right-hand side in our result, as we can see in our output.

[02:14] I want to show you how we can leverage these operators to do some more complex expressions. Here we have a list of activities. The main three in question here are three activities that are tied with a FunScore of 10.

[02:29] The first thing we're going to check is if our activity is "Board Games." If so, it wins, and it returns ActivityOne as our result. If it's false, then the OR kicks in, and it's going to continue looking for a truthy value.

[02:44] The next thing we're going to look for is "Teaching" in the ActivityTwo slot, and then for "Programming" in the ActivityTwo slot. If none of those evaluated to truthy, we're just going to compare the FunScore. If ActivityOne has a higher FunScore, we'll give that back. Lastly, we'll fall through to returning ActivityTwo.

[03:06] This is a useful tool because we can combine the "return right-hand side when all truthy" behavior of the AND operator with the "return the first truthy value we find" behavior of the OR operator to do some concise logical evaluations.

egghead

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at [email protected].

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

  • 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

JS Arithmetic Operators

  • Addition(+) Arithmetic Operator in JavaScript
  • Subtraction(-) Arithmetic Operator in JavaScript
  • Multiplication(*) Arithmetic Operator in JavaScript
  • Division(/) Arithmetic Operator in JavaScript
  • Modulus(%) Arithmetic Operator in JavaScript
  • Exponentiation(**) Arithmetic Operator in JavaScript
  • Increment(+ +) Arithmetic Operator in JavaScript
  • Decrement(--) Arithmetic Operator in JavaScript
  • JavaScript Arithmetic Unary Plus(+) Operator
  • JavaScript Arithmetic Unary Negation(-) Operator

JS Assignment Operators

  • Addition Assignment (+=) Operator in Javascript
  • Subtraction Assignment( -=) Operator in Javascript
  • Multiplication Assignment(*=) Operator in JavaScript
  • Division Assignment(/=) Operator in JavaScript
  • JavaScript Remainder Assignment(%=) Operator
  • Exponentiation Assignment(**=) Operator in JavaScript
  • Left Shift Assignment (<<=) Operator in JavaScript
  • Right Shift Assignment(>>=) Operator in JavaScript
  • Bitwise AND Assignment (&=) Operator in JavaScript
  • Bitwise OR Assignment (|=) Operator in JavaScript
  • Bitwise XOR Assignment (^=) Operator in JavaScript
  • JavaScript Logical AND assignment (&&=) Operator
  • JavaScript Logical OR assignment (||=) Operator
  • Nullish Coalescing Assignment (??=) Operator in JavaScript

JS Comparison Operators

  • Equality(==) Comparison Operator in JavaScript
  • Inequality(!=) Comparison Operator in JavaScript
  • Strict Equality(===) Comparison Operator in JavaScript
  • Strict Inequality(!==) Comparison Operator in JavaScript
  • Greater than(>) Comparison Operator in JavaScript
  • Greater Than or Equal(>=) Comparison Operator in JavaScript
  • Less Than or Equal(

JS Logical Operators

  • NOT(!) Logical Operator inJavaScript
  • AND(&&) Logical Operator in JavaScript
  • OR(||) Logical Operator in JavaScript

JS Bitwise Operators

  • AND(&) Bitwise Operator in JavaScript
  • OR(|) Bitwise Operator in JavaScript
  • XOR(^) Bitwise Operator in JavaScript
  • NOT(~) Bitwise Operator in JavaScript
  • Left Shift (
  • Right Shift (>>) Bitwise Operator in JavaScript
  • Zero Fill Right Shift (>>>) Bitwise Operator in JavaScript

JS Unary Operators

  • JavaScript typeof Operator
  • JavaScript delete Operator

JS Relational Operators

  • JavaScript in Operator
  • JavaScript Instanceof Operator

JS Other Operators

  • JavaScript String Operators
  • JavaScript yield Operator
  • JavaScript Pipeline Operator
  • JavaScript Grouping Operator

AND(&&) Logical Operator in JavaScript

JavaScript Logical And(&&) Operator or Logical Conjunction Operator operates on a set of operands and returns true only if all the operands are true otherwise returns false. It operates the operands from left to right and returns false whenever the first falsy value is encountered.

The Logical AND(&&) Operator can also be used on non-boolean values also. AND operator has higher precedence than the OR operator.

Example 1: In this example, we will use the AND operator on normal values.

Example 2: In this example, we will use the AND operator on function calls

Supported Browsers:

We have a complete list of JavaScript Logical Operators, to learn about those please go through JavaScript Logical Operator article.

Please Login to comment...

Similar reads.

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Bitwise AND (&)

The bitwise AND ( & ) operator returns a number or BigInt whose binary representation has a 1 in each bit position for which the corresponding bits of both operands are 1 .

Description

The & operator is overloaded for two types of operands: number and BigInt . For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt AND if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number bitwise AND. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

The operator operates on the operands' bit representations in two's complement . Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit , second bit to second bit , and so on. The operator is applied to each pair of bits, and the result is constructed bitwise.

The truth table for the AND operation is:

Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:

For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading 0 bits, and negative BigInts having an infinite number of leading 1 bits.

Bitwise ANDing any number x with -1 returns x converted to a 32-bit integer. Do not use & -1 to truncate numbers to integers; use Math.trunc() instead.

Using bitwise AND

Specifications, browser compatibility.

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

  • Bitwise operators in the JS guide
  • Bitwise AND assignment ( &= )

Learning JavaScript double question mark (??) or the Nullish Coalescing Operator

by Nathan Sebhastian

Last Updated Jan 23, 2022

Reading time: 4 minutes

javascript double ampersand assignment

When you’re inspecting JavaScript code, you may find an expression using a double question mark ( ?? ) as in the code below:

The double question mark is a logical operator that returns the expression on the right-hand of the mark when the expression on the left-hand is null or undefined

This operator is also known as the Nullish Coalescing Operator. It’s a new feature introduced in JavaScript ES2020 that allows you to check for null or undefined values in a more concise way.

Nullish Coalescing Operator syntax

The syntax for the Nullish Coalescing Operator is very simple. It consists of two question marks ?? placed between two expressions.

Here’s an example:

The code above assigns the firstName variable value as the value of the username variable.

When the firstName value is null or undefined , then the value Guest will be assigned instead:

You can also write it this way:

As you can see, you don’t need an if-else statement to check for null or undefined values.

Why JavaScript needed this operator?

The Nullish Coalescing Operator was created as an improved alternative to the OR operator || .

The OR operator was originally created to provide a default or fallback value when the left-hand expression is falsy, or evaluates to false .

But after some real-world uses, it’s clear that there are times when developers want to return values that are considered falsy, such as 0 and an empty string ( "" )

The use of OR operator will prevent you from returning any falsy values at all. Consider the following example:

By using the Nullish Coalescing Operator, you will only replace exactly null and undefined values with the right-hand value.

The Nullish Coalescing Operator can be used with any type of value, including numbers, strings, and objects.

Several use cases for the Nullish Coalescing Operator

The Nullish Coalescing Operator is useful in a variety of situations where you need to check for null or undefined values and provide a default value.

Here are several examples of common use cases:

Handling missing function arguments

When a function is called, it’s possible that some of the arguments may be omitted.

The Nullish Coalescing Operator can be used to provide default values for a missing argument as follows:

Accessing object properties

When working with objects, it’s possible that a property may not exist or is undefined .

The Nullish Coalescing Operator can be used to safely access object properties and provide a default value when the property is missing:

Choosing between a variable and a constant

You may want to select a value from a variable or a constant if the variable is null or undefined :

As you can see, the Nullish Coalescing Operator is a great feature that can make your code more concise and reliable.

Using ?? with || and && operators

For safety reasons, the double question mark can’t be used together with JavaScript OR ( || ) and AND ( && ) operators without parentheses () separating the operators.

For example, the following code tries to see if either firstName or lastName variable can be used as the value of username before using "Guest" as its value:

This is because JavaScript won’t be able to determine which operator it needs to evaluate first. You need to use parentheses to clearly indicate the priority of the evaluations.

The following code will first evaluate the expressions inside the parentheses:

And that’s how you combine the Nullish Coalescing Operator with either AND or OR operator.

The JavaScript double question mark is also known as the Nullish Coalescing Operator. It’s a logical operator that simply returns the right-hand expression when the left-hand expression is either null or undefined .

The Nullish Coalescing Operator is an improved OR operator that allows you to return 0 and an empty string "" as a valid value for your application.

This article also shows you a few examples where the Nullish Coalescing Operator is useful.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.

Learn more about this website

Connect with me on Twitter

Or LinkedIn

Type the keyword below and hit enter

Click to see all tutorials tagged with:

IMAGES

  1. Double The Numbers In JavaScript

    javascript double ampersand assignment

  2. Beginner JavaScript Tutorial 13 Assignment Operators

    javascript double ampersand assignment

  3. JavaScript Operators.

    javascript double ampersand assignment

  4. JavaScript compound assignment operators

    javascript double ampersand assignment

  5. SQL Double Ampersand Substitution

    javascript double ampersand assignment

  6. Double Ampersand in C++

    javascript double ampersand assignment

VIDEO

  1. Double Letter Assignment

  2. Python Assignment Operators || ( &= ),( |= ),( ^= ) (forward double angle brackets is equal to)

  3. JavaScript

  4. SS25 Basic Command, Control Operator, Semicolon, Ampersand, Double Pipe, Vertical Bar

  5. How Does The Double && Work In JavaScript? #javascript #webdevelopment #softwareengineer

  6. Essa feature do #TypeScript não é muito comum!

COMMENTS

  1. javascript

    Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false. In other words, Javascript does not coerce the operands to boolean values unless it has to. 4 && 5 Returns 5, not true. In your case, if the first expression is undefined (which is convertible to false), then ctx will be false, and the ...

  2. Logical AND (&&)

    Description. Logical AND ( &&) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned. If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called ...

  3. Logical AND assignment (&&=)

    Description. 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 short-circuiting of the logical AND operator. For example, the following does not throw an error, despite x being const:

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

  5. An Introduction to JavaScript Logical Operators By Examples

    JavaScript uses the double ampersand (&&) to represent the logical AND operator. The following expression uses the && operator: let result = a && b; Code language: JavaScript (javascript) If a can be converted to true, the && operator returns the b; otherwise, it returns the a. This rule is applied to all boolean values.

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

  7. JavaScript logical AND (&&) symbol explained

    by Nathan Sebhastian. Posted on Apr 15, 2022. Reading time: 2 minutes. JavaScript logical AND operator is marked with two ampersand symbols ( && ). The operator is used to perform logical conjunction of the values you added as its operands. The logical AND operator returns true only when all operand values evaluate as true.

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

  9. JavaScript Assignment

    Use the correct assignment operator that will result in x being 15 (same as x = x + y ). Start the Exercise. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  10. JavaScript Operators

    Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more. ... JavaScript Assignment Operators. Assignment operators assign values to JavaScript variables. The Addition Assignment Operator (+=) adds a value to a variable.

  11. 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 statement (x = y) executes, and the value of y gets ...

  12. Javascript Shorthands: Ternary, Logical || and && Assignments

    let name let lastname = "Exists" name &&= "Tywen" lastname &&= "Kelly. When it comes to the logical AND assignment, denoted by &&=, the expression only assigns name to "Tywen" if name is truthy. name is actually falsy, as it is undefined, so name is not assigned the value "Tywen". lastname on the other hand is assigned a truthy value of "Exists ...

  13. Logical AND assignment (&&=)

    Short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). Logical AND assignment short-circuits as well meaning that x &&= y is equivalent to: x && (x = y); And not equivalent to the following which would always perform ...

  14. Logical Operators

    A JavaScript tutorial about 'Logical Operators' Tutorials; Contact; JavaScript: Logical Operators. ... The 'and' operator (expressed in JavaScript with a double ampersand - &&) is used to check if one expression and another is true. Both must be true for the condition to be true (and if used in an 'if statement', for the code to be executed). ...

  15. Expressions and operators

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

  16. Double && (and) Double || (or) = Double Functionality

    With the OR operator, if the left-hand side is undefined, it will return the entire value of the right-hand side. [01:39] The AND operator is similar in that it can return one of the values being compared instead of a Boolean type. The differences are that it can only return the value on the right-hand side of the comparison and only if both ...

  17. AND(&&) Logical Operator in JavaScript

    JavaScript Logical And (&&) Operator or Logical Conjunction Operator operates on a set of operands and returns true only if all the operands are true otherwise returns false. It operates the operands from left to right and returns false whenever the first falsy value is encountered. The Logical AND (&&) Operator can also be used on non-boolean ...

  18. Bitwise AND (&)

    The & operator is overloaded for two types of operands: number and BigInt.For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt AND if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number bitwise AND.

  19. Learning JavaScript double question mark (??) or the ...

    The JavaScript double question mark is also known as the Nullish Coalescing Operator. It's a logical operator that simply returns the right-hand expression when the left-hand expression is either null or undefined. The Nullish Coalescing Operator is an improved OR operator that allows you to return 0 and an empty string "" as a valid value ...

  20. jquery

    You can't use spaces in the id of an element. You probably don't want to use an ampersand in the id of an element, but if you really need to you can escape the & using one backslash in the css selector, and two backslashes in the jQuery selector. In your example: var array = ["test1", "test2", "test\\&test"]; $(document).ready(function() {.