Javascript logical AND operator does not necessarily return boolean true false
If you came from other programming language, you might expect the Javascript boolean operator to return a boolean true or false. But this is not necessarily the case in Javascript. It will return a truthy or falsy value, but not necessarily a boolean. Everything in Javascript is either truthy or falsy.
Take the example, …
If alpha and beta are booleans, then sure Javascript will return a boolean true or false as expected. If both alpha and beta is true, then the condition is true. Otherwise, condition is false.
But if they were …
var alpha = “Hello”;
var beta = “World”;
The result of alpha && beta is “World”, which is truthy and the first if-branch will run.
This is because the rule for Javascript AND is …
If the first operand is truthy, return the second operand. Otherwise, return the first operand.
Since alpha of “Hello” is truthy, the operator returned beta, which is “World”.
If the second operand is a function invocation, the function will execute only if first operand is truthy. Here…
If there is a name value for “name”, the alert will occur. If name is an empty string (which is falsy), the greet function will not run.