Sub topic 2
Named Function Expressions for Recursion and Debugging
This chapter assumes you know basic JavaScript syntax, let and const, object methods, and callbacks such as setTimeout.
Named Function Expressions
A function expression can have its own name. That name is visible only inside the function body. This lets the function call itself without depending on the outer variable, which could be reassigned. The name also shows up in stack traces, which makes them easier to read than traces full of anonymous functions.
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
console.log(factorial(5)); // 120
console.log(typeof fact); // "undefined"Arrow Function Syntax and Implicit Returns
An arrow function with a concise body (one with no braces) returns its expression automatically. When the parameter list is a single plain parameter, you can leave out the parentheses. Braces start a block body, and a block body needs an explicit return. This causes a common bug: to return an object literal from a concise body, you must wrap it in parentheses. Without them, JavaScript reads { x: 1 } as a block that contains a label.
const square = x => x * x;
const makePoint = (x, y) => ({ x, y });
const noReturn = () => {
x: 1;
};
console.log(square(4)); // 16
console.log(makePoint(1, 2)); // { x: 1, y: 2 }
console.log(noReturn()); // undefinedDefault and Rest Parameters
A default parameter takes its default value when the argument is missing or undefined. A rest parameter (...rest) gathers the remaining arguments into a real array. A rest parameter must come last in the parameter list.
function greet(name = 'world', ...rest) {
return `Hello, ${name}! (${rest.length} extra)`;
}
console.log(greet()); // Hello, world! (0 extra)
console.log(greet('Ada', 1, 2, 3)); // Hello, Ada! (3 extra)How this Works in Regular and Arrow Functions
| Function form | Where `this` comes from |
|---|---|
| Regular function | How the function is called (the call site) |
| Arrow function | The surrounding scope where the arrow is defined (lexical `this`) |
const counter = {
count: 0,
startRegular() {
setTimeout(function () {
console.log(this === counter); // false
}, 0);
},
startArrow() {
setTimeout(() => {
this.count++;
console.log(this.count); // 1
}, 0);
}
};
counter.startRegular();
counter.startArrow();Exercise
Why does const f = () => { value: 42 }; return undefined, and how do you fix it?
Show answer
JavaScript reads the braces as a block body that contains a label, so the function has no return value. Wrap the object in parentheses to return it: () => ({ value: 42 }).
Exercise
Inside a method, a setTimeout callback needs to use the method's this. Which function form should the callback use?
Show answer
Use an arrow function. It takes this from the enclosing method, while a regular function callback gets its this from how setTimeout calls it.