JavaScript – Modern Operators

&&, ||, ??

Operators can use ANY data type, return ANY data type, and can be used for short-circuiting

console.log(3 || 'Nothing'); // returns the first truthy value (3)
console.log('' || 'Nothing')// Nothing
console.log(true || 'Alternative') // true
console.log(undefined || null) // null (null is truthy, undefined is not

Returns the first true value of an argument and then stops (short-circuits)

Can use this instead of terniary arguments

const myVar = trueArgument ? trueArgument : falseAction;
const myVar = argument || falsAction;

&& operator works in the opposite way

Will return the first falsey or all of them if they are all truthy

myFunction && myFunction('arg'); Checks that functions exists, if not then argument ends.

?? Nullish Coalescing Operator

This is used to avoid the issue if 0 should not be a falsey value.

Nullish: null and undefined only (not 0 or ”)

Other logical operators (ES6)

||=, &&=, ??=

myVariable ??= 10; // sets value to 10 if it is nullish

myVariable &&= '<anonymous>'; // resets value to annonymous if it exists

Leave a Reply

Your email address will not be published. Required fields are marked *