Friday, September 27, 2024
Google search engine
HomeLanguagesJavascriptWhat are the Helper functions ?

What are the Helper functions ?

The functions that perform some part of the computation of other functions are termed helper functions

They are named as per their work, i.e. they help the main function to look more clean, precise, and readable by giving descriptive names to some of the computations involved. Also, helper functions once declared, can be used anywhere in the program, thus, enhancing the reusability of code.
The following examples would make the use of helper functions clear.

Example 1: Let us suppose we have to write a function that takes an array of strings str as an input and returns another array pal, where pal[i] is “Yes” if str[i] is a palindrome and it returns “No” otherwise. There can be two ways to solve this problem, one without using any helper function and the other using it. 

Javascript




<script>
     // Without using helper functions
  
     var str = ["gfg", "radar", "article", "neveropen", "racecar"];
     var pal = [];
  
      function palArray(str) {
          for (let i = 0; i < str.length; i++) {
              let temp = str[i];
              let n = temp.length;
              let check = true;
              for (let j = 0; j < n / 2; j++) {
                  if (temp[j] != temp[n - j - 1]) {
                      check = false;
                      break;
                  }
              }
              if (check == true)
                  pal.push("Yes");
              else
                  pal.push("No");
          }
          return pal;
      }
  
    palArray(str);
  
    for (var i = 0; i < 5; i++) {
        console.log(str[i] + " " + pal[i]);
    }
</script>


Output:

gfg Yes
radar Yes
article No
neveropen No
racecar Yes

Javascript




<script>
    // Using helper functions
  
    var str = ["gfg", "radar", "article", "neveropen", "racecar"];
    var pal = [];
  
    // Defining a helper function to check 
    // whether a string is palindrome or not
    function checkPal(s){
        let n = s.length;
            for (let i = 0; i < n / 2; i++) {
                if (s[i] != s[n - i - 1]) {
                    return false;
                }
            }
        return true;
    }
  
    function palArray(str) {
        for (let i = 0; i < str.length; i++) {
            let temp = str[i];
  
            if (checkPal(temp)==true)
                pal.push("Yes");
            else
                pal.push("No");
        }
        return pal;
    }
  
    palArray(str);
  
    for (var i = 0; i < 5; i++) {
        console.log(str[i] + " " + pal[i]);
    }
  
</script>


Output:

gfg Yes
radar Yes
article No
neveropen No
racecar Yes

Example 2: As a second example for the usage of helper functions, let us assume we need to print the average of various parameters such as height, weight, etc. of players in a team. One way would be writing the same code again and again to compute the average for each parameter which would clutter the code.
The other way would be to use a helper function that calculates the average of the array passed to it as an argument. The helper function can be invoked in the main function used to calculate and print averages. This enhances the code’s reusability.

Javascript




<script>
    //Without using helper functions
  
    var heights=[172,166,180,175,170,182,176,165,162];
    var weights=[68,70,74,70,65,82,75,66,60];
    var ages=[20,19,23,19,20,21,24,22,21];
  
    function printAverages(heights,weights,ages){
        let heightSum=0,weightSum=0,ageSum=0;;
        for(let i=0;i<heights.length;i++){
            heightSum+=heights[i];
        }
        let avgHeight=heightSum/heights.length;
        for(let i=0;i<weights.length;i++){
            weightSum+=weights[i];
        }
        let avgWeight=weightSum/weights.length;
        for(let i=0;i<ages.length;i++){
            ageSum+=ages[i];
        }
        let avgAge=ageSum/ages.length;
        console.log("Average Height - " + avgHeight);
        console.log("Average Weight - " + avgWeight);
        console.log("Average Age - " + avgAge);
    }
    printAverages(heights, weights, ages);
  
</script>


Output:

Average Height - 172
Average Weight - 70
Average Age - 21

Javascript




<script>
  
    //Using helper functions
  
    var heights = [172, 166, 180, 175, 170, 182, 176, 165, 162];
    var weights = [68, 70, 74, 70, 65, 82, 75, 66, 60];
    var ages = [20, 19, 23, 19, 20, 21, 24, 22, 21];
  
    //Defining a helper function that calculates average
    function calcAverage(array) {
        let sum = 0;
        for (let i = 0; i < array.length; i++) {
            sum += array[i];
        }
        return sum / array.length;
    }
    function printAverages(heights, weights, ages) {
        let avgHeight = calcAverage(heights);
        let avgWeight = calcAverage(weights);
        let avgAge = calcAverage(ages);
        console.log("Average Height - " + avgHeight);
        console.log("Average Weight - " + avgWeight);
        console.log("Average Age - " + avgAge);
    }
    printAverages(heights, weights, ages);
  
</script>


Output:

Average Height - 172
Average Weight - 70
Average Age - 21

Now, it becomes clear from the examples above that how helper functions help us to enhance code reusability, write clean code and improve code readability. Also, a helper function once defined, can also be used in various other functions which require similar computation. 
Thus, whenever we find the same computation multiple times in any function or program, we should create a separate (helper) function for that computation and call that function instead to make the code more readable and clean.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments