JavaScript · Course navigation

JavaScript Functions

Write reusable logic.

On this page

The concept

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

Code example

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
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

Behind the scenes

How JavaScript processes this code

A JavaScript engine parses and runs the source. A function body runs when the function is called. console.log writes to the console.