JavaScript Logical OR assignment (||=) Operator
Last Updated :
06 Jan, 2023
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.
Javascript
<script>
let name = {
firstName: "Ram" ,
lastName: "" ,
};
console.log(name.firstName);
name.firstName ||= "Shyam" ;
console.log(name.firstName);
console.log(name.lastName);
name.lastName ||= "Kumar" ;
console.log(name.lastName);
</script>
|
Output :
"Ram"
"Ram"
""
"Kumar"
Example 2: This example shows the use of the JavaScript Logical OR assignment (||=) Operator.
HTML
< 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 :
JavaScript Logical OR assignment (||=) Operator
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
Share your thoughts in the comments
Please Login to comment...