JavaScript / Functions

Functions in practice

Write functions with several parameters, store their result in a variable, and put loops, conditions and the remainder operator inside them. Baccalaureate

In a swimming relay each team swims three strokes, and we want each team's total time. We write a function with three parameters separated by commas, and pass three arguments in the same order when calling it. The returned value can be stored in a variable to use later:

JavaScript
function sum(freestyle, breaststroke, backstroke) {
  let time = freestyle + breaststroke + backstroke;
  return time;
}
let teamRed = sum(39.5, 60.5, 58.5);
let teamBlue = sum(40, 62, 58);
console.log(teamRed);
console.log(teamBlue);
console.log("The fastest time is " + Math.min(teamRed, teamBlue));
Console
158.5
160
The fastest time is 158.5
TermIn the example
Parameters: names in the definitionfreestyle, breaststroke, backstroke
Arguments: values in the call39.5, 60.5, 58.5
Storing the result in a variablelet teamRed = sum(39.5, 60.5, 58.5);
Arguments can be variables, as in Math.min(teamRed, teamBlue). Parameter names belong to the function only; they have nothing to do with variable names outside it.

A loop and a condition inside a function

In the school raffle a ticket wins if its number is divisible by 7, meaning the remainder after dividing by 7 is zero: num % 7 == 0. To count the winning tickets from 0 to 999 we need a counter starting at 0, a loop over every number, a condition that increases the counter, and then we print the counter after the loop:

JavaScript
let count = 0;
for (let i = 0; i <= 999; i++) {
  if (i % 7 == 0) {
    count++;
  }
}
console.log(count);
Console
143

Put the same program inside a function and make the last number a parameter, so it can be reused for any number of tickets:

JavaScript
function countWinners(lastNum) {
  let count = 0;
  for (let i = 0; i <= lastNum; i++) {
    if (i % 7 == 0) {
      count++;
    }
  }
  return count;
}
console.log(countWinners(999));
console.log(countWinners(100));
Console
143
15

Some functions print the result themselves, so they do not need return. Call them on their own line without console.log:

JavaScript
function printWinners(from, to) {
  for (let i = from; i <= to; i++) {
    if (i % 7 == 0) {
      console.log(i + " wins");
    }
  }
}
printWinners(120, 150);
Console
126 wins
133 wins
140 wins
147 wins
Put return count; after the loop. Inside it, the function would leave on the first turn with the wrong number, because return ends the function immediately.

Practice

1Fill in the blankCurriculum practice

Create the function calculation3 with the parameters a, b and c that returns their product a * b * c, so it prints 24.

JavaScript Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
function ___(___) {
  let result = ___;
  return result;
}
console.log(calculation3(2, 3, 4));
Console
Press Run to see the result.
2Edit the programCurriculum practice

Before the last line, declare a variable num1 holding the result of calc3(5, 10, 15). Then, at the end, declare num2 holding calc3(4, 4, 4) and print it.

JavaScript Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
function calc3(a, b, c) {
  let result = a * b * c;
  return result;
}

console.log(num1);
Console
Press Run to see the result.
3Fill in the blankCurriculum practice

Declare teamGreen as the result of sum(41, 59.5, 60), then complete the last line so it prints the smallest time among teamRed, teamBlue and teamGreen.

JavaScript Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
function sum(freestyle, breaststroke, backstroke) {
  let time = freestyle + breaststroke + backstroke;
  return time;
}
let teamRed = sum(39.5, 60.5, 58.5);
let teamBlue = sum(40, 62, 58);
let teamGreen = ___;
console.log("The fastest time is " + Math.min(___));
Console
Press Run to see the result.
4Edit the programCurriculum practice

Complete the program to count the winning tickets in a smaller raffle, from 0 to 500: a for loop with i from 0 while i <= 500, and inside it, if i divided by 7 leaves a remainder of 0, add 1 to count. It prints 72.

JavaScript Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
let count = 0;

console.log(count);
Console
Press Run to see the result.
5Fill in the blankCurriculum practice

Write the condition: if i is divisible by 3, print i.

JavaScript Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
for (let i = 1; i < 10; i++) {
  if (___) {
    console.log(i);
  }
}
Console
Press Run to see the result.
6Write the programExtra practice

Create a function timesTable with the parameter n that prints the n times table from 1 to 5 in the form 7 x 1 = 7. Then call it with 7.

JavaScript Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Console
Press Run to see the result.
7Write the programExtra practice

Create a function countPrizes with two parameters, students and every, that returns how many students win a prize: students are numbered 1 to students, and each one whose number is divisible by every wins. Print countPrizes(40, 4), then countPrizes(100, 6) (the output is 10, then 16).

HintA counter starting at 0, a loop from 1 to students, and return count; after the loop.
JavaScript Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Console
Press Run to see the result.

Key points

  • A function with several parameters function f(a, b, c) is called with the same number of arguments in order: f(1, 2, 3).
  • Store the result in a variable: let x = f(1, 2, 3);, and pass variables as arguments.
  • A function can contain a loop and a condition; n % 7 == 0 means n is divisible by 7.
  • return ends the function at once, so put it after the loop; a function that prints by itself does not need it.