搬運自Jess Telford的回答
// returns: undefined
// explanation: an empty block with an implicit return
((name) => {})()(
// returns: 'Hi Jess'
// explanation: no block means implicit return
(name) => "Hi " + name
)("Jess")(
// returns: undefined
// explanation: explicit return required inside block, but is missing.
(name) => {
"Hi " + name;
}
)("Jess")(
// returns: 'Hi Jess'
// explanation: explicit return in block exists
(name) => {
return "Hi " + name;
}
)("Jess")(
// returns: undefined
// explanation: a block containing a single label. No explicit return.
// more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
(name) => {
id: name;
}
)("Jess")(
// returns: {id: 'Jess'}
// explanation: implicit return of expression ( ) which evaluates to an object
(name) => ({ id: name })
)("Jess")(
// returns: {id: 'Jess'}
// explanation: explicit return inside block returns object
(name) => {
return { id: name };
}
)("Jess");
MDN之說明
(參數1, 參數2, …, 參數N) => { 陳述式; }
(參數1, 參數2, …, 參數N) => 表示式;
// 等相同(參數1, 參數2, …, 參數N) => { return 表示式; }
// 只有一個參數時,括號才能不加:
(單一參數) => { 陳述式; }
單一參數 => { 陳述式; }
//若無參數,就一定要加括號:
() => { statements }
// 用大括號將內容括起來,返回一個物件字面值表示法:
params => ({foo: bar})
// 支援其餘參數與預設參數
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
statements }
// 也支援 parameter list 的解構
var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; f(); // 6
若要在promise chain( 如.then()中 )使用非arrow function的話,注意必須有 ' return ' 才能串起chain