Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

javascript - How to use arrow function with || operator

Using Babel, I can see that

 callback = () => {};

compiles to

callback = function callback() {};

which is what I expect. However I get an error when I try to use it with ||

callback = callback || () => {}

Which I'd expect to be equivalent to

 callback = callback || function(){};

Why is this an error? Also, is there a more correct ES6 version of this familiar syntax?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It fails because that is just not valid syntax.

Use the following to make it work:

callback = callback || (() => {})

If you don't wrap it that way, it would be interpreted as if you typed the following. But that is invalid syntax.

callback = (callback || ()) => {}

To extend on the evaluation of the assignment, see the specification of the AssignmentExpression. It consist of a ConditionalExpression or an ArrowFunction (or some other expressions I will disregard). So the interpreter will try to use your code as a conditional. But the () itself is not valid in that context as an expression is expected inside that ParenthesizedExpression. As a result, it will fail. If you instead group the expression as callback || (() => {}) both sides of the LogicalOrExpressions are valid expressions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...