JavaScript

How to Perform Arithmetic Operations in JavaScript

Perform arithmetic operations in JavaScript, including addition subtraction multiplication division and modulus

6/9/2022
0 views

JavaScript is a versatile programming language used to build dynamic web applications. One of the most basic yet fundamental things in any programming language is performing arithmetic operations. Whether you're building a calculator, performing mathematical logic, or manipulating numbers, JavaScript provides a rich set of operators to handle arithmetic. Here, I’ll guide you to perform arithmetic operations in JavaScript, including addition, subtraction, multiplication, division, and modulus.

Basic Arithmetic Operators

JavaScript supports the following basic arithmetic operations:

  • Addition (+)

  • Subtraction (-)

  • Multiplication (*)

  • Division (/)

  • Modulus (%)

Let's explore each of these operators with examples. Here I’m taking inputs from the user and storing the value in two variables by getting them by its id.

let a = (document.getElementById("num1").value * 1);
let b = (document.getElementById("num2").value * 1);

1. Addition (+)

The + operator is used to add two numbers together.

document.getElementById("sum").innerHTML = a + b;

2. Subtraction (-)

The - operator subtracts one number from another.

document.getElementById("sub").innerHTML = a - b;

3. Multiplication (*)

The * operator multiplies two numbers.

document.getElementById("mul").innerHTML = a * b;

4. Division (/)

The / operator divides one number by another.

document.getElementById("div").innerHTML = a / b;

5. Modulus (%)

The modulus operator returns the remainder of a division. It's useful when you need to know if one number is divisible by another. The % operator returns the remainder of a division of one number by another.

document.getElementById("mod").innerHTML = a % b;

Conclusion

Understanding these arithmetic operators is fundamental to building logic in your JavaScript programs. Once you master these, you’ll be well on your way to handling complex calculations, data manipulation, and much more in JavaScript!

JavaScriptArithmetic OperationsJS

Related Examples

Mashable is a global, multi-platform media and entertainment company For more queries and news contact us on this
Email: info@mashablepartners.com