breaktop breaktop - 3 months ago 20
Javascript Question

Boolean conditions in console.log() statement

I've just noticed that you can put boolean expressions within console.log e.g.

console.log("hey" || 2)
where in this case
would be printed out to the console window.

I'm not 100% sure exactly how
determines what to print when there is a condition within it.


There is a concept of truthy and falsy values in JavaScript. Non empty string is considered truthy value, so "hey" evaluates to true and is printed, because the part after || is not evaluated in that case.

In general truthy are all values that are not false, 0, "", null, undefined, or NaN.

MDN defines evaluation of OR expressions as follows:

Logical OR (||) expr1 || expr2: Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

So by this logic console.log() prints first truthy expression in your statement. If you were to try console.log(null || 2), then 2 would be printed out.