Hello World, every year, new features get added to the JavaScript language.This enables developers write better code which translates into awesome products.
In 2021, the Logical assignment operators were added to the language. Its main objective is to assign values to variables.
In this post, we will learn how to effectively utilize the logical assignment operators. Let's get started.
The Logical assignment operators
ES2021 introduced three logical assignment operators:
- Logical OR assignment operator (
||=
) - Logical AND assignment operator (
&&=
) - Nullish coalesing assignment operator (
??=
)
The Logical assignment operators combine the logical operators and assignment expression.
If you have forgotten what Logical operators are, here is my post on Logical Operators to help refresh your mind.
Alright, now let's discuss the Logical OR assignment operator (||=
)
What is 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
The syntax is as below
x ||= y
In the syntax, the ||=
will only assign the value of y
to x
if x
is falsy.
Let's take a look at the ||
operator first.
The Logical OR operator ||
returns the *first *truthy
value in an expression.
Consider an example below
let firstName = "";
let noName = "Guest"
console.log(firstName || noName);
The output will be Guest
.
- In the example above, the
firstName
variable is an empty string""
, and thenoName
variable is a string ( a string stores a sequence of characters). - Empty strings
""
are consideredfalsy
values while non-empty strings(eg."emma"
) aretruthy
values. - Because the
||
operator returns the first truthy value, the value stored in thenoName
variable (ie.Guest
) will logged to the console.
Note that : 0
, null
, undefined
, NaN
and ""
are classified as falsy
values.
Assigning a value to a variable using the ||=
operator.
Consider a situation where you want to assign a truthy
value to a variable storing a falsy
value
Let's see how you can achieve that using the logical OR assignment operator (||=
)
You can do this (long method)
let firstName=""
let noName="Guest"
//assign the "Guest" value to the firstName variable
firstName = firstName || noName
Let's understand the code above
- The expression on the right :
firstName || noName
is evaluated first. - Since the
||
operator returns the first truthy value, it will return the valueGuest
- Using the
=
(assignment operator), the valueGuest
is then assigned to thefirstName
variable which has afalsy
value - Now, anytime we
console.log(firstName)
, we get the valueGuest
The example above can be simplified using the logical OR assignment operator (||=
).
// long form
firstName = firstName || noName
//using the ||= syntax
firstName ||= noName;
Example 2
let age; // age is undefined
age ||=28;
console.log('The value of age is now ', age )
The output will be
The value of age is now 28
-The truthy
value of 28 will be assigned to the age
variable which has a falsy
value
- The
age
now has a value of 28
Example 3
You can also assign a truthy
value to a property in an object if the property is falsy
.
Take a look at the code below
let userDetails= {
firstName: "Emmanuel",
userName:"" // userName stores a falsy value
}
//using the ||=
userDetails.userName ||="emma"
console.log('The username is now ', userDetails.userName)
The output will be
The username is now emma
In the example above
- The
||
operator evaluates the expression and returns the firstytruthy
value ("emma"
) - The
truthy
value is now assigned to theuserDetails.username
property sinceuserDetails.username
isfalsy
If the first operand is a truthy
value, the logical OR assignment operator (||=
) will** not assign the value of the second operand to the first. **
Consider the code below
let userDetails = {
firstName: "Emmanuel",
userName : "efk"
}
userDetails.userName ||="emma";
console.log('The username is now ', userDetails.userName)
The output will be
The username is now efk
- Because the
userDetails.userName
property istruthy
, the second operand was not evaluated
In summary, the x ||= y
will assign the value of y
to x
if x
is falsy
.
Using the Logical AND assignment operator (&&=
)
Sometimes you may want to assign a value to a variable even if the initial variable has a value. This is where the logical AND assignment operator (&&=
) comes in.
What is the logical AND assignment operator ?
The logical AND assignment operator only assigns
y
tox
ifx
istruthy
*The syntax is as below *
x &&= y
- if the operand on the left side is
truthy
, the value ofy
is then assigned tox
Let's see how this was done previously
let firstName = "Emmanuel"
let userName = "efk"
if(firstName){
firstName = userName
}
console.log(firstName)
The output will be efk
.
- The
if
evaluates the condition in the parenthesis()
- If the condition is
true
then the expression inside the curly braces{}
gets evaluated - Because the
firstName
istruthy
, we assign the value ofuserName
tofirstName
.
Using &&=
in the same example as above
let firstName = "Emmanuel"
let userName = "efk"
firstName &&= userName
console.log("the first name is now ", firstName)
The output will be
the first name is now efk
- Because
firstName
is a truthy value, the value ofuserName
is now assigned tofirstName
The &&=
operator is very useful for changing values. Consider the example below
Example 2
let userDetails = {
id: 1,
firstName: "Emmanuel",
lastName: "Fo"
}
userDetails.lastName &&="Fordjour"
console.log(userDetails)
The output will be
{id: 1, firstName: 'Emmanuel', lastName: 'Fordjour'}
- userDetails.lastName is a
truthy
value hence the right operandFordjour
is assigned to it.
Example 3
In the code below, we given an object, and our task is to change the id
to a random number between 1 and 10.
Let's see how that can be done using the &&=
let userDetails = {
id: 1,
firstName: "Emmanuel"
}
//generate random number
function genRandomNum(){
return (Math.floor((Math.random() * 10 ) + 1))
}
//assign the random number to the userDetails.id
userDetails.id &&= genRandomNum()
console.log("the id is now ", userDetails.id)
The output will vary depending on the random number returned, here is an example.
the id is now 3
In summary, the &&=
operator assigns the value of the right operand to the left operand if the left operand is truthy
The nullish coalescing assignment operator (??=
)
The nullish coalescing assignment operator only assigns
y
tox
ifx
isnull
orundefined
.
The syntax is as below
x ??= y
Let's see how to use the nullish coalescing assignment operator
Example 1
let firstName; //undefined
firstName ??="Emmanuel";
console.log('first name is now ', firstName)
The output will be
first name is now Emmanuel
- The
firstName
variable isundefined
- We now assign the value of the right operand to
firstName
- firstName now has the value of
Emmanuel
.
Example 2
Adding a missing property to an object
let userDetails = {
firstName: "Emmanuel"
}
userDetails.userName ??="Guest";
console.log(userDetails)
The output will be
{firstName: 'Emmanuel', userName: 'Guest'}
- The userDetails.userName is
undefined
hence nullish - The nullish coalescing assignment operator
??=
then assigns the stringGuest
to theuserDetails.userName
- Now the
userDetails
object has propertyuserName
.
In summary
- The logical OR assignment
(x ||= y)
operator only assignsy
tox
ifx
isfalsy
. - The logical AND assignment
(x &&=y)
operator will assigny
tox
ifx
istruthy
- The nullish coalescing assignment operator will assign
y
tox
ifx
isundefined
ornull
.
I trust you have learnt something valuable to add to your coding repository.
Is there anything that wasn't clear to you ? I would love to read your feedback on the article.
Writing with love from Ghana. Me daa se (Thank you)
Top comments (1)
Logical operators are expressions used to make conditions. It might be confusing at first but once you practice you will understand. After all, you don't learn coding without practice. I had to use NVQ assignment writing help which has been a life saver for me.