8. Arithmetic#

Arithmetic operations are the foundation of many programming tasks. They allow you to perform calculations, manipulate numbers, and build more complex logic in your programs.

8.1. Operators#

JavaScript provides several operators for performing arithmetic:

Addition

let sum = 5 + 3;
console.log(sum); // Prints: 8

Subtraction

let difference = 10 - 4;
console.log(difference); // Prints: 6

Multiplication

let product = 6 * 7;
console.log(product); // Prints: 42

Division

let quotient = 20 / 5;
console.log(quotient); // Prints: 4

Modulus

Finds the remainder when one number is divided by another.

let remainder = 10 % 3;
console.log(remainder); // Prints: 1

Power (Exponent)

The first number is the base and the second number is the power. For example you would read 4**2 as ‘4 to the power of 2’, i.e., which is 16.

let exponent = 4**2;
console.log(exponent); // Prints: 16

8.2. Order of Operations (PEMDAS)#

JavaScript follows the order of operations, also known as PEMDAS:

  1. P:spelling:ignore:arentheses

  2. E:spelling:ignore:xponents

  3. M:spelling:ignore:ultiplication (and m:spelling:ignore:odulo) and D:spelling:ignore:ivision

  4. A:spelling:ignore:ddition and S:spelling:ignore:ubtraction

Example: Multiplication happens before addition

let result = 5 + 2 * 3;
console.log(result); // Prints: 11

Example: Parentheses are evaluated first

let resultWithParentheses = (5 + 2) * 3;
console.log(resultWithParentheses); // Prints: 21

8.3. Special Cases#

8.3.1. Dividing by Zero#

In JavaScript, dividing by zero results in Infinity or -Infinity for positive and negative numbers, respectively.

console.log(5 / 0); // Prints: Infinity
console.log(-5 / 0); // Prints: -Infinity

8.3.2. Not a Number (NaN)#

If an arithmetic operation involves invalid inputs (like dividing a string by a number), JavaScript returns NaN (Not a Number).

console.log("hello" / 2); // Prints: NaN