JavaScript Logical OR assignment (||=) Operator
This operator is represented by x ||= y and it is called a logical OR assignment operator. If the value of x is falsy then the value of y will be assigned to x.
When we divide it into two parts it becomes x || ( x = y ).
It checks if x is true or false, if the value of x is falsy then it runs the ( x = y ) block and the value of y gets stored into x and if the value of x is truthy then the value of the next block ( x = y ) does not execute.
Syntax :
x ||= y
is equivalent to
x || (x = y)
Example 1: This example shows the use of the JavaScript Logical OR assignment (||=) Operator.
<script>
let name = {
firstName: "Ram",
lastName: "",
};
console.log(name.firstName);
// Changing the value using logical
// OR assignment operator
name.firstName ||= "Shyam";
// But value does not change because
// name.firstName is truthy
console.log(name.firstName);
console.log(name.lastName);
// Changing the value using logical
// OR assignment operator
name.lastName ||= "Kumar";
// The value changes because name.lastName is falsy
console.log(name.lastName);
</script>
Output :
"Ram" "Ram" "" "Kumar"
Example 2: This example shows the use of the JavaScript Logical OR assignment (||=) Operator.
<h1 style="color:green">Geeksforgeeks</h1>
<p id="print_arr"></p>
<script>
let arr = [1, 2, "apple", null, undefined, []]
// Replace each falsy values with "gfg"
arr.forEach((item, index)=>{
arr[index] ||= "gfg"
})
document.getElementById("print_arr").innerText = arr.toString();
</script>
Output :
.png)
We have a complete list of Javascript Operators, to check those please go through the Javascript Operators Complete Reference article.
Supported browsers:
- Chrome 85
- Edge 85
- Firefox 79
- Safari 14