In JavaScript, you can use the Math
object to perform various mathematical operations. To find the sum of two or more numbers, you can use the +
operator.
Note: there is no built-in Math.sum() method in JavaScript. However, you can create your sum()
function using the reduce()
method to sum up an array of numbers.
JavaScript Math sum example
Simple example code using the +
operator to find the sum of two numbers:
const a = 5;
const b = 7;
const sum = a + b;
console.log(sum); // Output: 12
Let’s create a sum()
function using the reduce()
method and find the sum of any array of numbers, like this:
<!DOCTYPE html>
<html>
<body>
<script>
function sum(numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
const numbers = [1, 2, 3, 4, 5];
const total = sum(numbers);
console.log("Array sum", total);
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS math topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version