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 and15is passed as an argument.- The code block inside of
getFahrenheit()callsmultiplyByNineFifths()and passes15as an argument. multiplyByNineFifths()takes the argument of15for thenumberparameter.- The code block inside of
multiplyByNineFifths()function multiplies15by(9/5), which evaluates to27. 27is returned back to the function call ingetFahrenheit().getFahrenheit()continues to execute. It adds32to27, which evaluates to59.- Finally,
59is 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.