What Javascript Boolean Statements Return and Variable Assignments


TLDR;

  • Boolean statements return the last assessed value.
  • When a boolean statement breaks, the value that broke it is the last assessed value.
  • The last assessed value can be assigned to a variable.

const x = true && 1 && {} && [] && ( false || 1 === 2 || 7 || true);
// 7;

Boolean Statements Evaluate Using the ‘Truthy’ (True/False) Association of The Values

As we know, Javascript has an associated boolean value for any given value.

For example, an empty object, {}, evaluates to true, and a null value, null, evaluates to false.

So, this example:

true && 1 && {} && [] && ( false || 1 === 2 || 7 || true)

Becomes:

true && true && true && true ( false || false || true || true)

Boolean Statements are Evaluated Lazily

As always in software engineering, we’re looking to minimize the amount of computations a machine has to do to accomplish a task. We do this to maximize efficiency of an operation. Javascript follows suit and evaluates boolean statements in a minimalistic, lazy way, cutting off as soon as the statement’s logic breaks.

true && 1 && {} && [] && ( false || 1 === 2 || 7 || true)

Is actually:

true && true && true && true ( false || false || true || <Never Executed>)

The statement breaks at the number 7 and then leaves the evaluation. It does not continue on to the next element (value true) to see whether if fits within the logic or not. Because 7 breaks the logic, all required effort is finished.

Boolean Statements Return the Last Assessed Value

Whatever the last assessed value of a boolean statement is returned out of the statement.

Because our statement below breaks at 7:

true && 1 && {} && [] && ( false || 1 === 2 || 7 || true)

The entire statement evaluates to 7.

So, we could effectively do something like this:

const x = true && 1 && {} && [] && ( false || 1 === 2 || 7 || true);

And expect the following assignment:

console.log(‘The value of “x” is: ’, x)
// The value of “x” is: 7

So, we can define a variable based on the output of a boolean statement.

Useful Examples

So, how is a returned value from a boolean statement useful?

Defaulting a value in a function:

function z (x) { 
 y = x || 7; 
 return y;
}
z(); // 7
z(12); // 12

Passing forward the accumulator in an array reduce method.

const arr = [1, 2, 3];
const r = arr.reduce((acc, cur) → {
 return (acc[cur]=cur * 2) && acc;
}, {});
/* r is 

 ‘1’: 2, 
 ‘2’: 4, 
 ‘3’: 6

*/

Criteria Checking

const a = (1 === 2); 
const b = { x: 1 };
if ( a || b ) { 
 // Executes..
}
if ( a && b ) { 
 // Does Not Execute..
}

Closing

That booleans return their last assessed values is a simple concept. I found that after I’ve explained it fully to myself that I’ve utilized it more and more in my implementations. Perhaps you will, too. Enjoy!