Functions and closures in JavaScript
Declarations, arrows, defaults, rest, and closures.
function greet(name, greeting = "Hello") {
return `${greeting}, ${name}!`;
}
const square = (x) => x * x;
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
const makeCounter = () => {
let count = 0;
return () => ++count;
};
const counter = makeCounter();
counter();
const value = counter();
How it works
- Default parameters fill in missing arguments.
- Arrow functions are concise and capture
thislexically. makeCounterreturns a closure over its own state.
Keywords and builtins used here
constfunctionletreturn
The run, in numbers
- Lines
- 15
- Characters to type
- 301
- Tokens
- 98
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 65 seconds.
Step 1 of 3 in Functions, step 14 of 43 in Language basics.