Logic Operators with Non-boolean values boolean coercion
suggest changeLogical OR (||), reading left to right, will evaluate to the first truthy value. If no truthy value is found, the last value is returned.
const a = 'hello' || ''; // a = 'hello'
const b = '' || []; // b = []
const c = '' || undefined; // c = undefined
const d = 1 || 5; // d = 1
const e = 0 || {}; // e = {}
const f = 0 || '' || 5; // f = 5
const g = '' || 'yay' || 'boo'; // g = 'yay'
Logical AND (&&), reading left to right, will evaluate to the first falsy value. If no falsy value is found, the last value is returned.
const a = 'hello' && ''; // a = ''
const b = '' && []; // b = ''
const c = undefined && 0; // c = undefined
const d = 1 && 5; // d = 5
const e = 0 && {}; // e = 0
const f = 'hi' && [] && 'done'; // f = 'done'
const g = 'bye' && undefined && 'adios'; // g = undefined
This trick can be used, for example, to set a default value to a function argument (prior to ES6).
const foo = function(val) {
// if val evaluates to falsy, 'default' will be returned instead.
return val || 'default';
}
console.log( foo('burger') ); // burger
console.log( foo(100) ); // 100
console.log( foo([]) ); // []
console.log( foo(0) ); // default
console.log( foo(undefined) ); // default
Just keep in mind that for arguments, 0 and (to a lesser extent) the empty string are also often valid values that should be able to be explicitly passed and override a default, which, with this pattern, they won’t (because they are falsy).
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents