JavaScript/TypeScript中无需返回值时忽略箭头函数隐式返回是否为不良实践?
forEach a Bad Practice Here? Great question! Let’s unpack this step by step.
First, let’s clarify the core point: the subscription.unsubscribe() method returns void (it doesn’t produce any meaningful value). Since Array.prototype.forEach ignores the return value of its callback function entirely, your original implicit return version:
ngOnDestroy() { this.subscriptions.forEach(subscription => subscription.unsubscribe()); }
functions exactly the same as the explicit block version:
ngOnDestroy() { this.subscriptions.forEach(subscription => { subscription.unsubscribe(); }); }
So functionally, there’s no harm here. But is it a bad practice? It depends on context and team conventions, but here’s what to consider:
- Readability for the team: If some members of your team aren’t deeply familiar with arrow function implicit returns, they might pause to wonder why you’re returning the result of
unsubscribe()(even though it’s void). The explicit block makes it crystal clear: we’re just executing an action, not intending to return anything. - Consistency with style guides: Many teams adopt a rule where implicit returns are only used for callbacks that exist to produce a value (like in
map,filter, orreduce), while side-effect-only callbacks (likeforEach) use explicit blocks. Sticking to this consistency avoids cognitive friction when reading code. - Future-proofing (a tiny concern): While extremely unlikely, if the return type of
unsubscribe()ever changed (or if you modified the callback to do something that returns a value later), the implicit return could lead to unintended behavior. The explicit block eliminates this trivial risk.
Final Takeaway
There’s no functional issue with the implicit return version, but using the explicit block is generally a safer, more readable choice—especially in team environments. It makes your code’s intent unambiguous, which is always a win for maintainability.
内容的提问来源于stack exchange,提问作者user1902183

