Hi, I just learnt about Javascript Functions and would like to know the method for finding out average using Arrays and Functions in JS. I have linked a screenshot of my code, can you please help me?
1 Answer
const scores = [60, 75, 21, 43];
const avg = scores.reduce((accumulator, currentValue) => accumulator + currentValue)/scores.length;
console.log(avg);
The Reduce function when used on an array will iterate over its entirety, with each iteration having access to a Accumulator (A single variable shared across all iterations) and a CurrentValue (Represents the current interation value). Using this you can add all the values together and divide the result by the array's length.
This can also be replaced with a function, "(accumulator, currentValue) => ..." is a lambda expression and is basically just shorthand for "function funcNameHere(accumulator, currentValue) { ... }"
Lambda expressions can also declare a body just like a normal function. "(param) => { ... }"
return. That's not a valid attempt in my book.