Skip to content
Related Articles

Related Articles

JavaScript Logical OR assignment (||=) Operator
  • Last Updated : 25 Feb, 2021
GeeksforGeeks - Summer Carnival Banner

This operator is represented by x ||= y  and it is called 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:

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 :

HTML




<!DOCTYPE html>
<html>
<body>
  <h1>Hello 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>
    
</body>
</html>

Output :

Supported browsers:

  • Chrome 85
  • Edge 85
  • Firefox 79
  • Safari 14

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :