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?
3
Answers
Your solution works. To make it shorter and work with as few or many numbers you want you could do:
Read about spread syntax (the … used before nums) here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
And about the array method reduce here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
And about arrow functions here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Your solution looks good! You can extend your solution to find the average of any count of numbers by utilizing an array
Additionally, you could also utilize the spread syntax if you wanted to avoid creating an array manually:
When you return it, if you want to use that value, you should assign the returned value to a variable.
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:
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
Remember that the function must always take in an array as its arguments
Enjoy your journey into JavaScript. Hope this was helpful 🙂