Unveiling JavaScript: Arithmetic Operators

Unveiling JavaScript: Arithmetic Operators

Arithmetic Operators

JavaScript's arithmetic operators are your tools for performing calculations on numbers. These operators manipulate numeric values, represented as literals, variables, or expressions. They come in two flavors: unary (working on one value) and binary (working on two values). Understanding them unlocks powerful computations in your code.

Essential Arithmetic Operators

JavaScript provides a robust set of arithmetic operators with symbols you'll likely recognize:

  • Addition (+)

  • Subtraction (-)

  • Multiplication (*)

  • Division (/)

  • Modulus (%) (Remainder)

  • Increment (++) (Increase)

  • Decrement (--) (Decrease)

Operators in Action: Examples

Let's dive into how these operators work with practical examples:

Addition (+)

JavaScript

let x = 5, y = 10;
let sum = x + y; // sum will be 15 (5 + 10)

// Addition can also combine strings and numbers (sometimes)
let z1 = '10' + 3; // z1 becomes "103" (treats '10' as a number)
let z2 = '10' + '3'; // z2 becomes "103" (concatenates strings)

Subtraction (-)

JavaScript

let a = 20, b = 10;
let difference = a - b; // difference will be 10 (20 - 10)

// Subtraction works with strings that can be converted to numbers
let c = "20", d = "10";
let result = c - d; // result will be 10 (converts '20' and '10' to numbers)

Multiplication (*)

JavaScript

let p = 20, q = 10;
let product = p * q; // product will be 200 (20 x 10)

// Multiplication with strings (if convertible to numbers)
let r = "20", s = "10";
let result = r * s; // result will be 200 (converts '20' and '10' to numbers)

Division (/)

JavaScript

let m = 20, n = 10;
let quotient = m / n; // quotient will be 2 (20 / 10)

// Division handles edge cases:
let divisionResult = 100 / 0; // divisionResult will be Infinity

Modulus (%)

JavaScript

let dividend = 20, divisor = 9;
let remainder = dividend % divisor; // remainder will be 2 (20 divided by 9 leaves a remainder of 2)

Increment (++) and Decrement (--)

These operators adjust a variable's value by 1. They can be used in two ways:

  • Prefix (++num or --num) - Modify the value and then use it.

  • Postfix (num++ or num--) - Use the current value and then modify it.

JavaScript

let num1 = 10;
let num2 = ++num1; // Prefix increment: num1 and num2 become 11 (num1 is incremented first)

let num3 = 10;
let num4 = num3++; // Postfix increment: num3 becomes 11 but num4 remains 10 (num3 is used first, then incremented)

// Decrement works similarly:
let num5 = 10;
let num6 = --num5; // Prefix decrement: num5 and num6 become 9 (num5 is decremented first)

let num7 = 10;
let num8 = num7--; // Postfix decrement: num7 becomes 9 but num8 remains 10 (num7 is used first, then decremented)

By mastering these arithmetic operators, you'll equip yourself to tackle various mathematical challenges within your JavaScript applications.