Member-only story

Logical operators with non-boolean values

The code is shorter when the logical operators are used instead of IF conditions. Data visualization is even easier with ?? operator.

Marian C.
4 min readMay 24, 2021

&&, || and ?? operators return one of the two values used as their operands. The values can be of any type.

&&

value1 && value2 results in value2 when value1 is truthy and in value1 when value1 is falsy:

console.log(undefined && 'a'); //undefined
console.log(0 && 1); //0
console.log('a' && 'b'); //b

Basically, && is a shortcut for a function with an if statement:

function and(value1, value2) {
if (value1) return value2;
else return value1;
}

If the function and is used instead of && the code gets a bit longer:

console.log(and(undefined, 'a')); //undefined
console.log(and(0, 1)); //0
console.log(and('a', 'b')); //b

A typical use case of && is safely accessing a property of an object that can happen to be undefined.

Suppose we have an array of objects each describing a user. Some of the common properties are not defined in some users. The first user has name and score but no age. The second user has age but no name or…

--

--

Marian C.
Marian C.

Written by Marian C.

Java, JavaScript and SQL developer. Interested in data collection and visualization.

Responses (1)