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.
<script>
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;
}
</script>
<input id="nbr1"> + <input id="nbr2">
<button onclick="sumOfNbr()">Calculate the sum</button>
= <input id="sum">
Also Read:
- Difference Between encodeURIComponent() And encodeURI()
- Convert Comma Separated String Into An Array In JavaScript
- How To Check If A String Is Empty In JavaScript
- How To Sort An Array Of Numbers In JavaScript
- How To Return Multiple Values From A Function In JavaScript
- How To Get The Current URL With JavaScript
- How To Include A JavaScript File In Another JavaScript File
- How To Detect Screen Resolution With JavaScript
- How To parse JSON Into JavaScript
- How To Add Elements To An Array In JavaScript
- How To Generate A Timestamp In JavaScript
- How To Convert A JavaScript Object To JSON String
- How To Add An Element To The Beginning Of An Array
- How To Get The Value From The Input Field In JavaScript
- Adjust The iFrame Height To Fit With Content In JavaScript
- Call Two Functions From The Same onClick Event In JavaScript
- How To Detect When A Window Is Resized Using JavaScript
- How To Reset A Form With JavaScript
- How To Pass JavaScript Variables To PHP
- Difference Between PHP And JavaScript
- Armstrong Number In JavaScript
- How To Determine If A Number Is Odd Or Even In JavaScript
- How To Check If A Number Is A Palindrome In JavaScript
- How To Convert Strings To Uppercase In JavaScript
- How To Convert A String To Lowercase In JavaScript
- Code To Check If Age Is Not Less Than 18 Years In JavaScript
- How To Reverse A Number In JavaScript
- How To Check If A Number Is Prime Using JavaScript
- How To Find Factorial Of A Number In JavaScript
- Sum Of Two Numbers In JavaScript
- How To Display The Current Date And Time In JavaScript