Arithmetic Operators in JavaScript

 

JavaScript provides several arithmetic operators to perform mathematical calculations. Whether you want to add two numbers or divide a pizza among friends (without causing a riot), JavaScript has you covered. Let's dive into these operators!

1. Basic Arithmetic Operators

a) Addition (+)

The + operator is used for addition (but beware—it also concatenates strings!).

console.log(5 + 3); // 8 (Basic math still works!)
console.log("Hello" + " World"); // "Hello World" (String romance!)
console.log("5" + 3); // "53" (JavaScript thinks you're a poet, not a mathematician!)

b) Subtraction (-)

Used for, well, subtracting.

console.log(10 - 4); // 6 (No surprises here)
console.log("10" - 4); // 6 (JavaScript does the conversion for you!)
console.log("Hello" - 5); // NaN (JavaScript has no idea what you're doing)

c) Multiplication (*)

Used to multiply numbers.

console.log(6 * 3); // 18 (Nothing unusual)
console.log("6" * "3"); // 18 (JavaScript actually helping? Wow.)
console.log("Hello" * 5); // NaN (You can’t multiply words... yet.)

d) Division (/)

Used for division.

console.log(10 / 2); // 5 (Easy stuff)
console.log(10 / 0); // Infinity (Congrats, you broke math!)
console.log("10" / "2"); // 5 (JavaScript is weirdly accommodating)

e) Modulus (%)

Returns the remainder after division. Perfect for figuring out who gets the last slice of pizza.

console.log(10 % 3); // 1 (One slice left, fight for it!)
console.log(20 % 4); // 0 (No leftovers!)

f) Exponentiation (**)

Used to raise a number to a power.

console.log(2 ** 3); // 8 (2 raised to the power of 3, aka 2 * 2 * 2)
console.log(10 ** 0); // 1 (Everything to the power of 0 is 1, because math says so)

2. Increment and Decrement Operators

a) Increment (++)

Increases a value by 1. Perfect for counting how many times you've debugged your code.

let x = 5;
x++;
console.log(x); // 6 (One step closer to infinity!)

b) Decrement (--)

Decreases a value by 1. Good for counting down to deadlines.

let y = 10;
y--;
console.log(y); // 9 (The deadline looms closer...)

3. Fun with Arithmetic in JavaScript

JavaScript can sometimes act weird with arithmetic operations. Here are some examples that might make you question reality:

console.log("5" - - "2"); // 7 (Double negatives? JavaScript must have a law degree!)
console.log("10" * []); // 0 (An empty array is basically nothing, so... makes sense?)
console.log([] + []); // "" (Two empty arrays make an empty string. Sure, why not?)
console.log([] + {}); // "[object Object]" (Umm... okay?)
console.log({} + []); // 0 (JavaScript, you good?)

Conclusion

JavaScript arithmetic operators are powerful but can be tricky when dealing with different data types. Always be careful with type conversions to avoid unexpected results. If something breaks, just blame JavaScript and move on!

Post a Comment

0 Comments