-3

enter image description here

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?

5
  • 2
    Please see why we shouldn't post images of text :) Commented Aug 24, 2021 at 17:45
  • Please see the How to Ask page. What's the specific issue(s)? How to calculate an average? How to sum values in an array? How to find the length of an array? How to divide? (Yes, this is a hint.) Commented Aug 24, 2021 at 17:46
  • Does this answer your question? Finding the average of an array using JS Commented Aug 24, 2021 at 17:47
  • See this answer using ES6 and reduce: Commented Aug 24, 2021 at 17:48
  • 4
    Your "code" is just... return. That's not a valid attempt in my book. Commented Aug 24, 2021 at 17:55

1 Answer 1

-1

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) => { ... }"

Sign up to request clarification or add additional context in comments.

2 Comments

YMMV, but I believe (a) if there are multiple duplicates, (b) the OP didn't make an attempt to solve the problem, and (c) the OP doesn't describe the specific issue(s) they're having, an answer isn't super-appropriate.
Yes, rules are rules. Just giving a break considering they are brand new to this and trying not to discourage someone just learning for the first time. Mistakes will be made.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.