TutreNews Learn

Functions

Declaring functions

Goal: Write functions with parameters, defaults and return values · 9 min

function area(w, h = w) {
  return w * h;
}
area(3, 4); // 12
area(5);    // 25 (h defaults to w)

A function receives arguments in its parameters and gives back a value with return. Without return, the result is undefined. Missing arguments are undefined unless a default is given.

Functions are values: you can store them in variables, pass them to other functions and return them. That is the basis of everything in the next lessons.

Worked example: A function as an argument

  1. twice receives a function f.
  2. It calls f two times.
  3. twice(inc, 5) = inc(inc(5)) = 7.
function inc(x) { return x + 1; }
function twice(f, x) { return f(f(x)); }
console.log(twice(inc, 5));

Output:

7