声明 是一个具名函数语句;表达式 将一个函数分配给一个变量。实际区别在于 hoisting。
js
// Declaration — fully hoisted, callable before its line
declared();
() { ; }
();
expressed = () { ; };
函数声明会被 连同其函数体一起 hoisted,所以整个函数在执行到达它之前就存在了。函数表达式只是一个赋值给变量的值——在早期调用的时候,expressed 仍然是 undefined(使用 var 时)或处于 TDZ(使用 let/const 时)。
// expression — for callbacks, conditional definitions, arrow functions
const handler = () => doThing();
const fn = condition ? a : b;
arr.map(x => x * 2);
// declaration — clear, hoisted top-level functions
function calculateTotal(items) { ... }
声明对于顶级的具名函数可读性很好,并且受益于 hoisting(你可以在使用它们之后定义它们)。表达式对于 arrow 函数、回调函数、IIFE 和条件性地分配函数是必需的。Arrow 函数总是表达式。