The functions in JavaScript can be roughly divided into four categories:
- Functions that return a value.
- Functions that have side effects.
- Mixed functions.
- Pure functions.
Functions that return a value are those with a return
statement.
1function example() {
2 . . .
3
4 return true;
5}
The returned value can be used elsewhere. For example, you can save the output as a variable.
1let result = example();
Or used by other functions.
1console.log(example());
Functions with side effects are those that do not have a return
statement, but perform certain tasks on their own. For example, the following function prints a string to the console.
1function print(text) {
2 console.log(text);
3}
In most cases, the functions that return a value are the most useful, because they are more customizable and extensible. The returned value can be used later in other parts of the code, if you do need to create some side effects.
And, of course, a function could have both side effects and return a value.
1function print(text) {
2 console.log(text);
3
4 return true;
5}
Lastly, there are pure functions.
A pure function produces no side effects and does not rely on the side effects of other code, meaning it does not rely on variables that might change because of other functions or programs.
A pure function should always produce the same result when called with the same arguments. Here is an example of a pure function:
1function square(x) {
2 return x * x;
3}
This function square()
produces no side effect, and does not rely on the output of other functions. When called with the same argument, the function square()
will always produce the same result.
The following examples, on the other hand, are not pure functions:
1let taxRate = 0.1;
2
3function calculateTax(amount) {
4 return amount * taxRate;
5}
6
7function calculateTotal(amount) {
8 let tax = calculateTax(amount);
9 return amount + tax;
10}
Even though neither function produces a side effect, calculateTax()
relies on an external variable, taxRate,
which might be changed by some other programs, and calculateTotal()
relies on the output of calculateTax()
. So, neither function is pure.
Of course, that is not to say the non-pure functions are bad. It is completely OK for you to write functions that are not pure. In fact, it is very common for us to write functions that rely on other functions, which are called higher-order functions, as we are going to explain later.
The only issue is that the non-pure functions often require more careful designing and must go through rigorous testing to eliminate potential bugs.