Code highlights logo

Learn

Functions

Helper Functions

When writing complex code, it is common to encounter scenarios where a single function cannot handle all the necessary tasks. This is where helper functions come in handy. By creating separate helper functions for specific tasks, you can avoid repetition, improve code readability, and modularize your code.

Creating and Using Helper Functions

To create a helper function, you can follow the same steps as creating any other function. The only difference is that a helper function is not intended to be used on its own; instead, it is meant to be called within another function.

Here's an example of a helper function that calculates the average of two numbers:

1function calculateAverage(num1, num2) {
2 let sum = num1 + num2;
3 let average = sum / 2;
4 return average;
5}
6
7function calculateSumAndAverage(num1, num2) {
8 let sum = num1 + num2;
9 let average = calculateAverage(num1, num2);
10 console.log("Sum: " + sum);
11 console.log("Average: " + average);
12}

In the code above, the function calculateAverage is a helper function that takes two numbers as parameters and returns their average. Later in the calculateSumAndAverage function, we call the calculateAverage function to calculate the average of num1 and num2.


Instructions

1.

Declare a function named calculateVolume that takes three parameters: length, width, and height.

2.

Inside the calculateVolume function, call the calculateArea function with width and height as arguments.

3.

Multiply the result of the calculateArea function by length and return the result.

4.

Call the calculateVolume function with arguments 10, 20, and 30, and log the result to the console.

Sign up to start coding

Already have an account?

Sign In

Course content