CodeBlanks Logo Icon CodeBlanks

Summary - Functions

Combine arrow functions, default and rest to write a math helper.

Summary - Functions

In this group you saw five aspects of functions: definition (declaration and expression), returning values with return, the short arrow function form, default parameters for fallback values, and rest parameters for variable arguments.

You can combine these to write flexible helper functions. A 'calculator helper', for example: written as an arrow function, taking a default rate and processing as many numbers as you want with a rest parameter.

In the final task you will write a function that computes an average. It will take a variable number of values with a rest parameter and return their average. You will use arrow functions and reduce together.

Practice Calculator helper

Define an arrow function named apply: const apply = (rate = 10, ...nums) => nums.reduce((sum, n) => sum + n * rate / 100, 0);. Print the result of apply(20, 100, 200) (100*20/100 + 200*20/100 = 60) with console.log.

Starter code

index.js
// Define the apply arrow function and print the call result

Sample solution

index.js
const apply = (rate = 10, ...nums) =>
  nums.reduce((sum, n) => sum + n * rate / 100, 0);
console.log(apply(20, 100, 200));

Expected output

60

Practice Compute the average

Define an arrow function named average: const average = (...nums) => nums.reduce((sum, n) => sum + n, 0) / nums.length;. Print the result of average(10, 20, 30, 40) (100 / 4 = 25) with console.log.

Starter code

index.js
// Define the average arrow function and print the call result

Sample solution

index.js
const average = (...nums) =>
  nums.reduce((sum, n) => sum + n, 0) / nums.length;
console.log(average(10, 20, 30, 40));

Expected output

25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the concepts

Term Meaning
function greet Declaration
return n * 2 Returning a value
(a) => a * 2 Arrow function
rate = 18 Default parameter
...nums Rest parameter

2 What does the calculator helper take?

  • A single number
  • Two fixed parameters
  • Only an array
  • A default rate and rest numbers Correct answer

Explanation: a default rate plus rest numbers gives a flexible helper.

3 Arrow with a default parameter

Question
const greet = (name = ____) => 'Merhaba ' + name;
Answer
const greet = (name = 'Misafir') => 'Merhaba ' + name;

Explanation: arrow functions also use = value for defaults.

All lessons in Beginner