In the fun function, I want to return 1 if the boolean expression is true.
function fun() {
(1 == 1) && return 1;
}
alert(fun());
Of course, I can easily do this with if (1 == 1) return 1. However, I am wondering why the above code does not work. It triggers a “Uncaught SyntaxError: Unexpected token return” error in the console in Chrome.
Shouldn’t return 1 only run if (1 == 1) is true? Why does this not work?
It doesn’t work because the
&&operator needsexpressionsfor both of its operands. E.g.,returnstatements, however, are not (grammatically speaking)expressions.