logo
post image

Javascript Logical AND Assignment Operator

The logical AND assignment operator represented by &&= works like the assignment operator =, but assigns only when the left-hand side is a truthy value.

// set x to y only when x is truthy
x &&= y;

What is a truthy value ? A truthy value in Javascript is considered as true when considered under a boolean context. All values are considered truthy except the following values :

  • Boolean false
  • number 0
  • number -0
  • "" / '' / `` empty string
  • null
  • undefined
  • NaN — Not a number

Examples

// a is falsy as it is undefined
let a;
let b = 10;

a &&= b;

// "undefined"
console.log(a);
// a is truthy
let a = 5;
let b = 10;

a &&= b;

// 10
console.log(5);
// falsy as innerHTML is empty
document.querySelector("#target").innerHTML = "";

// assigment will not happen
document.querySelector("#target").innerHTML &&= '<span></span>';

// ""
console.log(document.querySelector("#target").innerHTML);

Use-Cases of Logical AND Assignment Operator

  • Shorten down code : Instead of first checking whether the value is truthy and then performing an assignment, it is better to use the logical AND assignment operator as will involve only a single line of code.

    let a = 10;
    
    if(a) {
    	a = 20;
    }		
    
    // does the same thing but in a shorter syntax
    a &&= 10;
    
  • Improving efficiency of DOM operations : The logical AND assignment operator gets and sets the value in a single shot. This can help in improving efficiency of some DOM methods as parsing and rendering operations are reduced.

    // access innerHTML property
    if(document.querySelector("#target").innerHTML != '') {
    	// access innerHTML property again
    	document.querySelector("#target").innerHTML = '<div>Test</div>';
    }
    
    // access innerHTML property only once
    document.querySelector("#target").innerHTML &&= '<div>Test</div>';
    

Browser Compatibility

Logical OR assignment operator is supported in all major browsers :

  • Chrome 85+ (to be released in August 2020)
  • Firefox 79+
  • Edge 85+ (to be released in August 2020)
  • Safari 14+