Spex3
    

JavaScript Arithmetic Operators ๐Ÿ”ข


    

    

JavaScript Arithmetic Operators ๐Ÿ”ข
Arithmetic operators in JavaScript are used to perform mathematical operations on numbers.

1๏ธโƒฃ List of Arithmetic Operators
Operator Symbol Example Result
Addition + 5 + 2 7
Subtraction - 5 - 2 3
Multiplication * 5 * 2 10
Division / 5 / 2 2.5
Modulus (Remainder) % 5 % 2 1
Exponentiation ** 5 ** 2 25

2๏ธโƒฃ Examples of Arithmetic Operators
โœ… 1. Addition (+)
Adds two numbers.


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


๐Ÿ“Œ Note: If a string is involved, + performs string concatenation.


console.log("Hello" + " World"); // "Hello World"
console.log("10" + 5); // "105" (Number 5 is converted to a string)


โœ… 2. Subtraction (-)
Subtracts the second number from the first.


let difference = 10 - 5;
console.log(difference); // 5


โœ… 3. Multiplication (*)
Multiplies two numbers.


let product = 4 * 3;
console.log(product); // 12


โœ… 4. Division (/)
Divides the first number by the second.


let quotient = 10 / 2;
console.log(quotient); // 5

๐Ÿ“Œ Note: If division results in a decimal, JavaScript keeps it.


console.log(10 / 3); // 3.3333...


โœ… 5. Modulus (%)
Returns the remainder of a division.


console.log(10 % 3); // 1 (10 รท 3 = 3 remainder 1)
console.log(15 % 4); // 3 (15 รท 4 = 3 remainder 3)


๐Ÿ“Œ Use Case: Checking if a number is even or odd


let num = 7;
console.log(num % 2 === 0 ? "Even" : "Odd"); // "Odd"


โœ… 6. Exponentiation (**)
Raises the first number to the power of the second.


console.log(2 ** 3); // 8 (2ยณ)
console.log(5 ** 2); // 25 (5ยฒ)


๐Ÿ“Œ Alternative: Using Math.pow()


console.log(Math.pow(2, 3)); // 8

3๏ธโƒฃ Special Cases in Arithmetic
โœ… 1. Division by Zero (/ 0)

console.log(10 / 0); // Infinity
console.log(-10 / 0); // -Infinity

๐Ÿ“Œ Note: JavaScript returns Infinity instead of throwing an error.

โœ… 2. NaN (Not a Number)

console.log("hello" * 5); // NaN
console.log(undefined + 1); // NaN

๐Ÿ“Œ Tip: Use isNaN(value) to check if a result is NaN.

๐ŸŽฏ Summary: Best Practices
โœ… Use +, -, *, /, %, ** for mathematical operations.
โœ… Watch out for type coercion with + when using strings.
โœ… Use % to check even or odd numbers.
โœ… Avoid operations that result in NaN.


    Date: 2025-03-29 00:00:00.000000