Open In App
Related Articles

JavaScript Logical OR assignment (||=) Operator

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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);
      
    // 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.

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

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


Last Updated : 06 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads