We can also use the return value of a function inside another function. These functions being called within another function are often referred to as helper functions. Since each function is carrying out a specific task, it makes our code easier to read and debug if necessary.
If we wanted to define a function that converts the temperature from Celsius to Fahrenheit, we could write two functions like:
function multiplyByNineFifths(number) {
return number * (9/5);
};
function getFahrenheit(celsius) {
return multiplyByNineFifths(celsius) + 32;
};
getFahrenheit(15); // Returns 59
In the example above:
getFahrenheit()
is called and15
is passed as an argument.- The code block inside of
getFahrenheit()
callsmultiplyByNineFifths()
and passes15
as an argument. multiplyByNineFifths()
takes the argument of15
for thenumber
parameter.- The code block inside of
multiplyByNineFifths()
function multiplies15
by(9/5)
, which evaluates to27
. 27
is returned back to the function call ingetFahrenheit()
.getFahrenheit()
continues to execute. It adds32
to27
, which evaluates to59
.- Finally,
59
is returned back to the function callgetFahrenheit(15)
.
We can use functions to section off small bits of logic or tasks, then use them when we need to. Writing helper functions can help take large and difficult tasks and break them into smaller and more manageable tasks.