How to compute the sum and average of elements in an array?
💻 Jump straight to code - employ JavaScript's mighty reduce()
:
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:
Strings disguised as numbers? Not on my watch!
Ensure proper computation by turning strings back to their true number self:
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:
Reusable code? Yes please!
Put your logic inside a function for easy access everywhere:
Keep it short and sweet with ES6 arrow functions
ES6 arrow functions - less writing, more coding:
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:
Modern JavaScript: Stay ahead of the game
Empower your code with spread syntax for one step ahead operations:
Asynchronous data: Keep promises
Async data? No worries, use Promises or async/await with array-pleasing methods.
Was this article helpful?