最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - short circuit with a return statement - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Dec 16, 2015 at 13:18 Danield asked Dec 15, 2015 at 14:51 DanieldDanield 126k37 gold badges234 silver badges265 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 14

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)

No, return is a statement, you cannot use it as a part of an AND expression.

You can transform your code to a single return statement though if you need that for some reason:

if (b) return a+b;
/* else */ ...

is (more or less) equivalent to

return b && a+b || (...);

Of course, in any code that you write by hand and read with your eyes, you should just an if statement anyway.

发布评论

评论列表(0)

  1. 暂无评论