- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- Remember language
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
Browser compatibility.
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
- Logical OR ( || )
- Nullish coalescing operator ( ?? )
- Bitwise OR assignment ( |= )
DEV Community
Posted on Feb 9, 2020
JavaScript OR Assignment Operator
In JavaScript, there may be times when you want to assign one variable to a non-null value. The JavaScript OR assignment operator can be used to quickly assign the value of a variable to one of two options based on one value and if it is null or undefined.
The below code shows a function called 'getNotNull' which takes two parameters 'a' and 'b'. If the value of 'a' is defined and isn't null, it is returned, otherwise, the variable 'b' is returned. This doesn't prevent a null value being returned though, as if both 'a' and 'b' are null then the value of 'b' will be returned and therefore a null value will be returned.
A ternary operator can also be used to the same effect. In the below code a ternary operator is used to set the value of the variable 'result' to either the value of 'a' if it defined and not null otherwise it will be set to the value 'b'. Again, this does not prevent a null value if both variables are null or undefined.
The JavaScript OR assignment operator is represented with two pipe '|' symbols. This can be used to achieve the same effect as the above two code snippets. The value of the 'result' variable will be assigned to the value of 'a' if it is defined or not null otherwise it will be assigned to the value of 'b'.
The OR assignment operator does not need to be used with variables, it can be used with raw values too. The below code snippet shows using the OR operator to set the value of the 'result' variable uses raw values, 'null' or the number '2'. The value of the 'result' variable will be 2 as the left side of the OR assignment operator is null.
The OR assignment operator can be used to assign the value of one variable to either one or another value based on if the first value is null or undefined. Using the OR assignment operator does not prevent the variable from being assigned a null or undefined value, if both sides of the OR assignment operator are null then the resulting value will also be null.
This post was originally published on https://acroynon.com
Top comments (14)
Templates let you quickly answer FAQs or store snippets for re-use.
- Joined Feb 5, 2018
You should replace "null" / "null or undefined" by "falsy".
And also have a look at the "??" operator.
Keep writing it is a good way to improve!
- Location United Kingdom
- Education Computer Science Bsc
- Work Senior Software Engineer
- Joined Nov 7, 2019
Yeah, you're correct, it is a "falsely" value that is evaluated, I didn't want to make this post too complicated, but great to mention this for the curious readers. Thanks
I am not sure what you mean by "??" operator, I have written a post on the ternary operator and I plan to write a post about the optional chaining operator ('?.') in the future.
Here is the related documentation:
developer.mozilla.org/en-US/docs/W...
Thanks, it seems like a more strict version of the OR assignment operator. Perhaps I shall create a post comparing the two
I think that you should point out the differences between falsy values (cf. developer.mozilla.org/en-US/docs/G... ) and null/undefined checks (with ??). I think that will add value to your post.
I think I shall leave this post as it is for now and cover the falsy values and the coalescing operator in separate posts, thank you for the feedback and ideas
Up to you, I just recommend you to be careful with the terms that you use in your post and in my opinion it is a good to support your posts with official references.
For example you function:
Doesn't work if you pass to it a falsy value like 0 or an empty string.
By being not precise you will assume wrong things (I have been there so many times, and it is still happening).
I would recommend the "you don't know js" by Kyle Simpson ( @getify ), to expand your knowledge.
Thanks for all the feedback. My plan isn't to fill every post with all the detail needed, at least not right now (I don't have the time to put that much time into each post). I mainly want to encourage people to begin to learn how to code, or experiment with something they haven't used before. I don't admit to knowing everything, but I don't want to overload the reader with too much information that reduces their interest in code. Again, thank you for all the feedback, I super appreciate it and I guarantee some readers will benefit from some of the links you've posted.
- Joined May 7, 2020
You’re talking about the regular OR-operator; the OR assignment -operator doesn’t exist in Javascript (unfortunately)
I consider the standard or operator the one used in if statement, for boolean logic. Then the or assignment operator being used to assign values to variables (assign this value, if its falsey assign this value instead). I could be completely wrong in my phrasing, but I think it makes a nice distinction between the two use cases
You can consider a melon a nail when you hit it with a hammer, but it’s not going to make sense to anybody.
I’m afraid the long and short of it is just that the OR-assignment operator ( ||= ) is not the OR-operator ( || ), sorry man.
Okay, thanks for the clarification
Okay thank you
Great stuff, do you think my explanation in this post is good?
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
This Month in Solid #9: SolidHack started, new fellow and API change 😎
Daniel Afonso - Nov 5
Creating Theme Systems in React with SCSS and Redux
M1dnightGMR - Nov 6
Understanding LinkedIn Authwall: How it Works, Benefits, and Implementing it on Your Website
Nikhil Soman Sahu - Nov 5
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
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:
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.
IMAGES
VIDEO