×

typescript · level 3 · unit 1 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A function is a value you can store and pass around.

In Level 1 every function started with the word function. There is a shorter way to write one: the . (price: number): number => price + 3 takes a price and hands back the price plus postage. The => arrow points from the parameters to the answer.

Functions are values, so they fit in boxes and can be passed to other functions. A function you pass in for another function to call is a . Its label is a , like (price: number) => number: what goes in, then what comes out.

The checker compares every callback with its function type. A callback that takes or hands back the wrong thing is stopped before anything runs.

const addPostage = (price: number): number => price + 3;
function applyToAll(prices: number[], change: (price: number) => number): number[] {
  const result: number[] = [];
  for (const price of prices) {
    result.push(change(price));
  }
  return result;
}
console.log(addPostage(10));
console.log(applyToAll([10, 25], addPostage));

Pass the box name, addPostage, with no brackets. Brackets would call it straight away and pass its answer instead.