Search code examples
javascriptfunctionaverage

Trying to return the average from 3 number using a function (JS)


I'm just playing with JS and trying to learn it.

I am trying to determine the average of three numbers; for that, I have defined a function with three parameters and declared parameter values.

But the function isn't returning the average, but when I run console.log, it shows the average.

function make_avg(num1, num2, num3) {
  var total = num1 + num2 + num3;
  var average = total / 3;
  return average;
}
make_avg(15, 20, 25);

I have tried with this code but am unable to return the average. Can you tell me the issues with my code and the possible solution?


Solution

  • When you return it, if you want to use that value, you should assign the returned value to a variable.

    const num = make_avg(15, 20, 25)
    // num will be equal to 20
    

    It actually depends on what you are rerturning and how you are using it. For example if you are returning a boolean value (true/false), you can put it in a conditional statement without assigning it to a variable. E.g:

    function isString(arg){
      return typeof arg === 'string'
    }
    
    // you can then say:
    
    if(isString('hello world')){
      console.log("yes, it is a string") // because the function will return true, this block will execute
    }
    

    EXTRAS

    Your function is kinda limited to only finding the average of three numbers. You can scale this up by instead passing an array of numbers, and then changing your function to add the numbers (using .reduce on the array) and then divide the sum by the length of the array (which is the number of digits). This can find the average of any amount. NOTE: I will give the code to do this next. You can try it out yourself before checking the code, or maybe check it out if you get stuck.

    MODIFIED AVERAGE FINDER FUNCTION

      function find_avg(arrOfNums) {
        var total = arrOfNums.reduce((a, b) => {return a + b}, 0)
        var average = total / arrOfNums.length;
        return average;
      }
    
    // let's test it out
    
      const avg = find_avg([1, 2, 3, 4, 5, 6])
      // avg will be 3.5
    

    Remember that the function must always take in an array as its arguments Enjoy your journey into JavaScript. Hope this was helpful :)