Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

short circuit with a return statement

As far as I understand, short-circuiting with the logical AND && operator works like the following:

Assuming I have the expressions a and b then a && b is the same as a ? b : a since

if a is truthy then the result will be b and if a is falsy then the result will be a (without even trying to resolve b)

That being the case why is the following (demo) code throwing a SyntaxError:

var add = function(a,b) {
  b && return a+b; // if(b) return a+b
  ...
}

Is there a way to short circuit with a return statement?

like image 439
Danield Avatar asked Dec 15 '15 14:12

Danield


People also ask

What is a short-circuit of the statement?

Short circuiting is an alternative way of using the logical AND or OR operators (& or |) e.g. a non short-circuit OR if(false | true) { } The first condition and second condition are both evaluated even if false is not true (which it always is). However it is was written as a short-circuit OR: if(false || true) { }

What is the purpose of a return statement in a function?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function. For more information, see Return type.

Is && short-circuit?

Short-circuit evaluationThe logical AND expression is a short-circuit operator. As each operand is converted to a boolean, if the result of one conversion is found to be false , the AND operator stops and returns the original value of that falsy operand; it does not evaluate any of the remaining operands.

Do Python if statements short-circuit?

The Python or operator is short-circuiting When evaluating an expression that involves the or operator, Python can sometimes determine the result without evaluating all the operands. This is called short-circuit evaluation or lazy evaluation. If x is truthy, then the or operator returns x . Otherwise, it returns y .


1 Answers

The && binary operator needs both parts to be expressions.

return something is a statement but not an expression (it doesn't produce a value, as a value wouldn't be useful when the function ends).

Just use

if (b) return a+b;

with the added benefit of an easier to read code.

Read more :

  • Expressions vs Statements
  • the return statement (EcmaScript spec)
  • logical operators (MDN)
like image 64
Denys Séguret Avatar answered Sep 21 '22 21:09

Denys Séguret