JavaScript Sum

In JavaScript, performing arithmetic operations like summing numbers is a common task. The + operator is used to add numbers or concatenate strings. In this page, we'll explore how to sum numbers in JavaScript and provide some examples for a better understanding.

Key Points on Summing Numbers in JavaScript:

Adding Two Numbers in JavaScript:

This is the simplest case of adding two numbers using the + operator.

Example


let num1 = 10;
let num2 = 20;
let sum = num1 + num2;
console.log("Sum: " + sum); // Output: Sum: 30

Output

Sum: 30

Adding Multiple Numbers:

You can add more than two numbers by extending the expression with additional operands.

Example

let num1 = 5;
let num2 = 10;
let num3 = 15;
let sum = num1 + num2 + num3;
console.log("Total Sum: " + sum); // Output: Total Sum: 30

Output

Total Sum: 30

Sum with Dynamic Inputs (Using Functions):

Sometimes, you may want to sum numbers dynamically. You can create a function to handle this.

Example


function sum(a, b) {
    return a + b;
}
let result = sum(10, 20);
console.log("Sum via Function: " + result); // Output: Sum via Function: 30

Output

Sum via Function: 30