Explain Codes LogoExplain Codes Logo

How to compute the sum and average of elements in an array?

javascript
functions
promises
callbacks
Alex KataevbyAlex Kataev·Oct 31, 2024
TLDR

💻 Jump straight to code - employ JavaScript's mighty reduce():

const nums = [1, 2, 3, 4, 5]; // Getting together and making a sum of it all const sum = nums.reduce((a, b) => a + b); // Sharing the loot equally const avg = sum / nums.length; console.log(`Sum: ${sum}, Avg: ${avg}`);

If one-liners are your thing: const avg = nums.reduce((a, b) => a + b) / nums.length;

Empty arrays: Check yourself before you wreck yourself

With empty arrays, performing a check is crucial to avert disaster:

const nums = []; // make sure you invite someone before throwing a party! const sum = nums.reduce((a, b) => a + b, 0); const avg = nums.length ? sum / nums.length : 0; console.log(`Sum: ${sum}, Avg: ${avg}`);

Strings disguised as numbers? Not on my watch!

Ensure proper computation by turning strings back to their true number self:

const nums = ["1", "2", "3", "4", "5"]; // the old switcheroo const sum = nums.reduce((a, b) => a + parseInt(b, 10), 0); const avg = sum / nums.length; console.log(`Sum: ${sum}, Avg: ${avg}`);

Enhancements for real programmers

Here are some tips and tricks to get your code running smoother than a buttered weasel.

Show off your results with document.write()

document.write() - because user-facing outputs like a bit of flair:

document.write(`Sum: ${sum}, Avg: ${avg}`);

Reusable code? Yes please!

Put your logic inside a function for easy access everywhere:

function calculateSumAndAverage(array) { const sum = array.reduce((a, b) => a + parseInt(b, 10), 0); const avg = array.length ? sum / array.length : 0; return { sum, avg }; } const results = calculateSumAndAverage(nums); console.log(`Sum: ${results.sum}, Avg: ${results.avg}`);

Keep it short and sweet with ES6 arrow functions

ES6 arrow functions - less writing, more coding:

const calculateSumAndAverage = (array) => { const sum = array.reduce((a, b) => a + parseInt(b, 10), 0); const avg = array.length ? sum / array.length : 0; return { sum, avg }; };

Expand your horizon

Large numbers: The bigger they come...

For arrays biggger than Godzilla, consider the performance of reduce() versus old school loops.

Beware of floats!

In JavaScript, decimal numbers might bite! Let's tame them:

const nums = [0.1, 0.2, 0.3]; // Be precise! Like a cat jumping onto a tiny shelf. const sum = nums.reduce((a, b) => a + b, 0).toFixed(2); const avg = (sum / nums.length).toFixed(2); console.log(`Sum: ${sum}, Avg: ${avg}`);

Modern JavaScript: Stay ahead of the game

Empower your code with spread syntax for one step ahead operations:

const sum = [...nums].reduce((a, b) => a + b, 0); const avg = sum / nums.length;

Asynchronous data: Keep promises

Async data? No worries, use Promises or async/await with array-pleasing methods.