JavaScript Arithmetic

What Are Arithmetic Operators in JavaScript?

Arithmetic operators in JavaScript let you perform mathematical operations on numbers. These operators are fundamental in coding, enabling tasks like calculations, loops and dynamic logic. Whether you’re building a calculator or performing complex data manipulation, these operators are your go-to tools.

Common JavaScript Arithmetic Operators

Here are the primary arithmetic operators in JavaScript:

OperatorDescriptionExampleResult
+Adds two numbers5 + 38
Subtracts one number from another5 – 32
*Multiplies two numbers5 * 315
/Divides one number by another10 / 25
%Finds the remainder after division10 % 31
**Raises a number to the power of another2 ** 38

Detailed Explanation of Arithmetic Operators

1. Addition (+)

The + operator adds two numbers or concatenates strings.

Example with Numbers:

let a = 10;
let b = 5;
console.log(a + b); // Output: 15

Example with Strings:

let firstName = "John";
let lastName = "Doe";
console.log(firstName + " " + lastName); // Output: John Doe

2. Subtraction (-)

The – operator subtracts one number from another.

Example:

let total = 20;
let discount = 5;
console.log(total - discount); // Output: 15

3. Multiplication (*)

The * operator multiplies two numbers.

Example:

let length = 5;
let width = 4;
console.log(length * width); // Output: 20

4. Division (/)

The / operator divides one number by another.

Example:

let total = 50;
let numPeople = 5;
console.log(total / numPeople); // Output: 10

5. Modulus (%)

The % operator returns the remainder of a division.

Example:

let dividend = 29;
let divisor = 5;
console.log(dividend % divisor); // Output: 4

6. Exponentiation (**)

The ** operator raises a number to the power of another.

Example:

let base = 3;
let exponent = 4;
console.log(base ** exponent); // Output: 81

Combining Arithmetic Operators

You can combine multiple arithmetic operations in a single expression. Use parentheses to control the order of operations.

Example:

let result = (10 + 5) * 2 - 4 / 2;
console.log(result); // Output: 28

Practical Use Case: Simple Calculator

Example Code:

let num1 = 8;
let num2 = 2;

console.log("Addition: " + (num1 + num2)); // Output: 10
console.log("Subtraction: " + (num1 - num2)); // Output: 6
console.log("Multiplication: " + (num1 * num2)); // Output: 16
console.log("Division: " + (num1 / num2)); // Output: 4
console.log("Remainder: " + (num1 % num2)); // Output: 0
console.log("Exponentiation: " + (num1 ** num2)); // Output: 64

Leave a Comment