Skip to content

Function Introduction

Functions are used to perform a specific task. They encapsulate a block of business logic and can be reused in different places. Functions are the building blocks of any program whether it is a text-based or visually based programming language.

Consider the following problem:

Calculate the area of a circle with radius 1, 2 and 3. If we do not use functions, we can calculate the area as follows:

1 * 1 * π

2 * 2 * π

3 * 3 * π

If we use a function to calculate the area, we can first define a function to calculate the area:

js
function area(r) {
  return r * r * π;
}

then call this function multiple times:

js
area(1);
area(2);
area(3);

Notice that the algorithm (calculate the area of a circle) is written once, and we can reuse it in different places. When the algorithm is more complex, we can greatly improve code reusability.