Skip to content
On this page

Function

We know the formula for the area of a circle is:

S = πr²

When we know the radius ( r ), we can calculate the area based on this formula. Suppose we need to calculate the areas of three circles of different sizes:

javascript
let r1 = 12.34;
let r2 = 9.08;
let r3 = 73.1;
let s1 = 3.14 * r1 * r1;
let s2 = 3.14 * r2 * r2;
let s3 = 3.14 * r3 * r3;

When the code shows a regular repetition, you need to be careful. Writing 3.14 * x * x each time is not only cumbersome, but if you want to change 3.14 to 3.1416 , you'll have to replace it everywhere.

With a function, we no longer need to write s = 3.14 * x * x each time; instead, we can use a more meaningful function call: s = area_of_circle(x) . The function area_of_circle itself only needs to be written once and can be called multiple times.

Basically, all high-level languages support functions, and JavaScript is no exception. JavaScript functions are not only "first-class citizens," but they can also be used like variables, providing powerful abstraction capabilities.

Abstraction

Abstraction is a very common concept in mathematics. For example:

Calculating the sum of a series, such as 1 + 2 + 3 + ... + 100, is quite inconvenient to write, so mathematicians invented the summation symbol $ \sum $, which allows us to express 1 + 2 + 3 + ... + 100 as:

n=1100n

This abstract notation is very powerful because when we see $ \sum $, we understand it as summation, rather than reverting to lower-level addition operations.

Moreover, this abstract notation is extensible. For instance:

n=1100(n2+1)

Reverting to addition operations becomes:

(1×1+1)+(2×2+1)+(3×3+1)+⋯+(100×100+1)

Clearly, through abstraction, we can focus on higher-level problem-solving without concerning ourselves with the specific calculations at a lower level.

Writing computer programs is the same; functions are the most basic form of code abstraction.

Function has loaded