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
firstNamevariable is an empty string"", and thenoNamevariable is a string ( a string stores a sequence of characters). - Empty strings
""are consideredfalsyvalues while non-empty strings(eg."emma") aretruthyvalues. - Because the
||operator returns the first truthy value, the value stored in thenoNamevariable (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 || noNameis evaluated first. - Since the
||operator returns the first truthy value, it will return the valueGuest - Using the
=(assignment operator), the valueGuestis then assigned to thefirstNamevariable which has afalsyvalue - 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
agenow 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 firstytruthyvalue ("emma") - The
truthyvalue is now assigned to theuserDetails.usernameproperty sinceuserDetails.usernameisfalsy
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.userNameproperty 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
ytoxifxistruthy
*The syntax is as below *
x &&= y
- if the operand on the left side is
truthy, the value ofyis 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
ifevaluates the condition in the parenthesis() - If the condition is
truethen the expression inside the curly braces{}gets evaluated - Because the
firstNameistruthy, we assign the value ofuserNametofirstName.
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
firstNameis a truthy value, the value ofuserNameis 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
truthyvalue hence the right operandFordjouris 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
ytoxifxisnullorundefined.
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
firstNamevariable 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
undefinedhence nullish - The nullish coalescing assignment operator
??=then assigns the stringGuestto theuserDetails.userName - Now the
userDetailsobject has propertyuserName.
In summary
- The logical OR assignment
(x ||= y)operator only assignsytoxifxisfalsy. - The logical AND assignment
(x &&=y)operator will assignytoxifxistruthy - The nullish coalescing assignment operator will assign
ytoxifxisundefinedornull.
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 (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.