You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中带{}的箭头函数执行机制——数组find函数异常解析

Why does adding curly braces to an arrow function in Array.find() return undefined?

Great question! Let's break down exactly what's happening here with JavaScript arrow functions and the Array.find() method.

First, let's revisit your test code for clarity:

// 数组声明
const phones = [{ brand: "Samsung", id: 10 }, { brand: "Apple", id: 20 }];
// 正确写法
let phone = phones.find(phone => phone.id === 10);
console.log("Correct result: ", phone);
// 错误写法
phone = phones.find(phone => { phone.id === 10; });
console.log("Wrong result: ", phone);

What's the key difference between the two arrow functions?

Arrow functions have two core syntax variations, and this is where your issue originates:

  • Implicit return (no curly braces): When you write an arrow function without curly braces (phone => phone.id === 10), JavaScript automatically treats the single expression after the arrow as the function's return value. So this callback returns the boolean result of phone.id === 10 (true when the id matches 10, false otherwise). The find() method uses this boolean to locate the first matching element, which gives you the correct result.

  • Explicit function body (with curly braces): Adding curly braces means you're defining a full function body. In this scenario, JavaScript does not automatically return any value unless you explicitly use the return keyword. Your incorrect callback { phone.id === 10; } runs the comparison expression but doesn't return it—so the function defaults to returning undefined.

Why does this break find()?

The Array.find() method requires its callback to return a truthy value for the element you want to retrieve. Since undefined is falsy, find() treats every element as a non-match. After checking all elements without getting a truthy return value, it returns undefined—which is your "wrong result".

Fixing the incorrect version

To make the curly brace version work as expected, just add the return keyword to explicitly return the comparison result:

phone = phones.find(phone => { return phone.id === 10; });

This matches the behavior of the implicit return version, giving you the correct matching element.

内容的提问来源于stack exchange,提问作者user11661871

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:41:34