How to Find the Sum of an Array of Numbers in JavaScript
All Answers
total answers (1)
Severity: 8192
Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated
Filename: libraries/Filtered_db.php
Line Number: 23
total answers (1)
Use the JavaScript
reduce()
MethodYou can use the
reduce()
method to find or calculate the sum of an array of numbers.The
reduce()
method executes the specified reducer function on each member of the array resulting in a single output value, as demonstrated in the following example:The 0 in the example above (line no-7) is the initialValue i.e. the value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used.
If the array is empty and no initialValue is provided, an error will be thrown. So it is safer to provide an initial value such as 0 if you're performing addition, and 1 if you're performing multiplication.
need an explanation for this answer? contact us directly to get an explanation for this answer