ILILCode
HomeJavaScriptFunctions & data

Functions: the verbs of your program

Declarations, arrow functions, defaults, rest parameters and functions that take functions.

Lesson 6 of 23 in JavaScript10 min2 exercises

A function packages a piece of work behind a name. It can take inputs (parameters), do something, and hand a value back with return. A function without a return statement returns undefined.

Three ways to write the same function
function double(n) {          // declaration, hoisted
  return n * 2;
}

const double2 = function (n) { // expression
  return n * 2;
};

const double3 = (n) => n * 2;  // arrow, shortest form

Defaults and rest parameters

Optional arguments
function greet(name = "friend") {
  return `Hello, ${name}!`;
}

greet();          // "Hello, friend!"
greet("Ada");     // "Hello, Ada!"

function sumAll(...numbers) {   // collects every argument
  return numbers.reduce((total, n) => total + n, 0);
}

sumAll(1, 2, 3);  // 6
sumAll();         // 0

Functions are values. You can store them in variables, put them in arrays, and pass them to other functions. A function that takes or returns a function is called a higher-order function — map, filter and reduce are the ones you will use daily.

Try it

Functions are values

main.js
console · output appears here

Exercises

Checked in your browser · hints and solutions included

01

Exercise

Apply a function twice

Write applyTwice(fn, value) that calls fn with value, then calls fn again with the first result, and returns the final value.

applyTwice((n) => n + 1, 5) → 7.

exercise.js
console · run your code or check the answer
02

Exercise

Sum anything you pass

Write sumAll(...numbers) that returns the total of every argument. With no arguments it returns 0.

sumAll(1, 2, 3) → 6.

exercise.js
console · run your code or check the answer