Sum Of Two Numbers In JavaScript: You can use the ‘+’ operator to add two numbers in JavaScript. Here is an example of how to add two numbers and store the result in a variable:

let num1 = 5;
let num2 = 10;
let sum = num1 + num2;
console.log(sum); // 15

You can also add two numbers and display the result directly, without storing it in a variable:

console.log(5 + 10); // 15

You can also use the += operator to add a number to a variable and assign the result to the same variable.

let num1 = 5;
num1 += 10;
console.log(num1); // 15

You can also use the sum() function from the math object to add numbers.

console.log(Math.sum(5,10)) // 15

It’s worth noting that you can also use the + operator to concatenate strings, not just add numbers. In case of concatenation, JavaScript will automatically convert the numbers to strings.

console.log("5" + "10"); // "510"

Therefore, it’s important to be aware of the data type of the operands when using the + operator.

Here is the simple calculator to calculate sum of two numbers using JavaScript.

         function sumOfNbr(){
             var nbr1, nbr2, sum;
             nbr1 = Number(document.getElementById("nbr1").value);
             nbr2 = Number(document.getElementById("nbr2").value);
             sum = nbr1 + nbr2;
             document.getElementById("sum").value = sum;
      <input id="nbr1"> + <input id="nbr2">
      <button onclick="sumOfNbr()">Calculate the sum</button>
      = <input id="sum">

Also Read:

Categorized in: