Loading course content...
Loading course content...
Code Playground is only enabled on larger screen sizes.
The functions in JavaScript can be roughly divided into four categories:
Functions that return a value are those with a return statement.
function example() {
// . . .
return true;
}The returned value can be used elsewhere. For example, you can save the output as a variable.
let result = example();Or used by other functions.
console.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.
function print(text) {
console.log(text);
}And, of course, a function could have both side effects and return a value.
function print(text) {
console.log(text);
return true;
}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:
function square(x) {
return x * x;
}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 example, on the other hand, are not pure functions:
function calculateTax(amount) {
return amount * taxRate;
}
function calculateTotal(amount) {
let tax = calculateTax(amount);
return amount + tax;
}Notice that calculateTax() relies on an external variable, taxRate, which might be changed by some other programs.
function calculateTax(amount) {
return amount * taxRate;
}
function calculateTotal(amount) {
let tax = calculateTax(amount);
return amount + tax;
}And calculateTotal() relies on the output of calculateTax().
function calculateTax(amount) {
return amount * taxRate;
}
function calculateTotal(amount) {
let tax = calculateTax(amount);
return amount + tax;
}So, neither functions are 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.
function calculateTax(amount) { return amount * taxRate; } function calculateTotal(amount) { let tax = calculateTax(amount); return amount + tax; }