JavaScript Functions

Write reusable logic.

JavaScript
const average = values => values.reduce((a, b) => a + b, 0) / values.length;
console.log(average([82, 91, 76, 95]));
Output
86

Explanation

Functions accept arguments and return results. An arrow function is a concise way to express a small function.

Explore the dry run
Guided walkthroughReady
1const average = values => values.reduce((a, b) => a + b, 0) / values.length;
2console.log(average([82, 91, 76, 95]));

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Create the average function; its body has not run yet.—
—
Pass four values into average. reduce sums them to 344, then divide by 4.return = 86
86