This behavior is called coercion . Coercion is an action that causes an object to behave like a different type, and logical operators can produce coercion when trying to access the value of an object for evaluation.
It is important to remember the table for truth and false values, because due to coercion different results can be obtained.
false creates false0 creates false"" creates falseNaN creates falsenull creates falseundefined creates false
Everything else creates true , including the text "0" and "false" , functions, arrays, and empty objects.
Given the rules for logical operators, there is a short circuit assessment in JavaScript, for example:
0 && 1;
Coercion is useful when you must check the defaults to prevent errors, for example.
function divide (a, b) { a = +a;
If you want to prevent NaN from returning, just add another constraint to the return statement:
return (b && a / b) || 0;
You can check other coercion cases: Coercion in JavaScript
Happy coding!
source share