Introduction
In this lab, we will dive into the world of JavaScript programming and explore the concept of calculating the average of numbers. Through hands-on exercises, you will learn how to use the Array.prototype.reduce() method and how to write a function to calculate the average of any number of values. By the end of this lab, you will have a solid understanding of how to use JavaScript to perform mathematical operations on arrays of numbers.
How to Calculate the Average of Numbers in JavaScript
To calculate the average of two or more numbers in JavaScript, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the built-in
Array.prototype.reduce()method to add each value to an accumulator, initialized with a value of0. - Divide the resulting sum by the length of the array.
Here's an example code snippet you can use:
const average = (...nums) =>
nums.reduce((acc, val) => acc + val, 0) / nums.length;
You can call the average function with an array or multiple arguments:
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2
Summary
Congratulations! You have completed the Average of Numbers lab. You can practice more labs in LabEx to improve your skills.