Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript Logical AND assignment (&&=) Operator

Improve Article
Save Article
  • Last Updated : 06 Jan, 2023
Improve Article
Save Article

This operator is represented by x &&= y, and it is called the logical AND assignment operator. It assigns the value of y into x only if x is a truthy value.

We use this operator x &&= y like this. Now break this expression into two parts, x && (x = y).  If the value of x is true, then the statement (x = y) executes, and the value of y gets stored into x but if the value of x is a falsy value then the statement (x = y) does not get executed.

Syntax :

x &&= y

is equivalent to 

x && (x = y)

Example: This example shows the basic use of the Javascript Logical AND assignment(&&=) operator.

Javascript




<script>
    let name = {
      firstName: "Ram",
      lastName: "",
    };
      
    console.log(name.firstName);
      
    // Changing the value using logical
    // AND assignment operator
    name.firstName &&= "Shyam";
      
    // Here the value changed because
    // name.firstName is truthy
    console.log(name.firstName);
      
    console.log(name.lastName);
      
    // Changing the value using logical 
    // AND assignment operator
    name.lastName &&= "Kumar";
      
    // Here the value remains unchanged 
    // because name.lastName is falsy
    console.log(name.lastName);
</script>

Output :

"Ram"
"Shyam"
""
""

Example 2: This example shows the basic use of the Javascript Logical AND assignment(&&=) operator.

HTML




<h1 style="color:green">
    Geeksforgeeks
</h1>
<h3>
    Javascript Logical AND assignment(&&=) operator
</h3>
<p id="print_arr"></p>
  
<script>
    let arr = [1, 2, "apple", null, undefined, []]
      
    // Replace each truthy values with "gfg"
      
    arr.forEach((item, index)=>{
      arr[index] &&= "gfg"
        })
      
        document.getElementById("print_arr").innerText = arr.toString();
        //console.log(arr)
</script>

Output :

Javascript Logical AND assignment(&&=) operator

Javascript Logical AND 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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!