Functions

Programming Languages · JavaScript Functions & Arrays · 14 min

Wrap code in reusable functions that take inputs and give back results.

Your first function

A function is a named, reusable chunk of code. You write it once, then call it by name with () whenever you need it.

function cheer() {
  console.log("Hooray!");
}
cheer(); // Hooray!
cheer(); // Hooray!

The code inside doesn't run until you call it.

  • Write a function sayHello that prints Hello!.

  • Call sayHello twice.

Parameters: giving a function input

A parameter is a variable in the brackets. When you call the function, the value you pass in fills it.

function shout(word) {
  console.log(word + "!!!");
}
shout("wow"); // wow!!!
  • Write greet(name) that prints Hello, then the name and !.

  • Call greet("Ada") and greet("Linus").

return: getting a result back

return hands a value back to whoever called the function. Then you can print it, store it, or use it in maths.

function add(a, b) {
  return a + b;
}
console.log(add(2, 3)); // 5

Printing shows a value; returning gives it back so the rest of your code can use it.

  • Write double(n) that returns n times 2.

  • Print double(21), then double(5).

Arrow functions

An arrow function is a shorter way to write a function. Store it in a const. If the body is one expression, it's returned automatically, no return needed.

const square = (x) => x * x;
console.log(square(3)); // 9
  • Write an arrow function triple that returns its input times 3.

  • Print triple(4), then triple(10).

Default parameters

Give a parameter a default with =. If the caller leaves it out, the default is used.

function order(drink = "water") {
  return `One ${drink}, please`;
}
console.log(order("tea")); // One tea, please
console.log(order());      // One water, please
  • Write welcome(name) that returns Welcome, + name + !, with name defaulting to "stranger".

  • Print welcome("Sam"), then welcome().

Put it together: tip calculator

Build two small functions where one uses the other. Functions calling functions is how bigger programs are built.

  • Write tip(bill, percent) that returns bill * percent / 100, with percent defaulting to 15.

  • Print tip(40), then tip(40, 20).

  • Write total(bill) that returns bill + tip(bill), and print total(100).

More in JavaScript Functions & Arrays

Previous: Conditionals · Next: Arrays