typestar

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

  1. Default parameters fill in missing arguments.
  2. Arrow functions are concise and capture this lexically.
  3. makeCounter returns a closure over its own state.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Functions, step 14 of 43 in Language basics.

← Previous Next →