logo
post image

Javascript Logical OR Assignment Operator

The logical OR assignment operator represented by ||= works like the assignment operator =, but assigns only when the left-hand side is a falsy value.

// set x to y only when x is falsy
x ||= y;

What is a falsy value ? A falsy value in Javascript is considered as false when considered under a boolean context. Falsy values include the following :

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

Examples

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

a ||= b;

// 10
console.log(a);
// a is not falsy
let a = 5;
let b = 10;

a ||= b;

// 5
console.log(5);
// innerHTML is set to empty
document.querySelector("#target").innerHTML = '';

document.querySelector("#target").innerHTML ||= '<div>Test</div>';

Use-Cases of Logical OR Assignment Operator

  • Shorten down code : Instead of first checking whether the value is falsy and then performing an assignment, it is better to use the logical OR assignment operator.

    let a = 0;
    
    if(a == 0) {
    	a = 10;
    }		
    
    // does the same thing but in a shorter syntax
    a ||= 10;
    
  • Improving efficiency of DOM operations : The logical OR 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+