Operators are the symbols that perform operations on values and variables. Let's break down the most common types.

1. Arithmetic Operators

These are used for performing mathematical calculations.

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulus - returns the remainder of a division)
  • ** (Exponentiation - raises the first operand to the power of the second)

Code Snippet:

JavaScript


let x = 10;
let y = 4;

console.log(x + y);  // 14
console.log(x - y);  // 6
console.log(x * y);  // 40
console.log(x / y);  // 2.5
console.log(x % y);  // 2 (10 divided by 4 is 2 with a remainder of 2)
console.log(y ** 2); // 16 (4 to the power of 2)

2. Assignment Operators

These assign values to variables.

  • = (Assignment)
  • +=, -=, *=, /=: Shorthand operators that perform an operation and assign the result.

Code Snippet:

JavaScript


let score = 100;

score += 50; // Equivalent to: score = score + 50;
console.log(score); // 150

score *= 2; // Equivalent to: score = score * 2;
console.log(score); // 300

3. Comparison Operators

These compare two values and return a boolean (true or false).

  • == (Equal to): Compares values after type coercion (e.g., "5" == 5 is true). Avoid this!
  • === (Strictly equal to): Compares both value and type without coercion. Always prefer this.
  • != (Not equal to)
  • !== (Strictly not equal to)
  • > (Greater than), < (Less than), >= (Greater than or equal to), <= (Less than or equal to)

Code Snippet:

JavaScript


const value1 = 5;
const value2 = "5";

console.log(value1 == value2);  // true (bad)
console.log(value1 === value2); // false (good)

console.log(10 > 5);   // true
console.log(10 <= 10); // true
console.log(value1 !== value2); // true

4. Logical Operators

These are used to combine multiple boolean expressions.

  • && (AND): Returns true only if both operands are true.
  • || (OR): Returns true if at least one operand is true.
  • ! (NOT): Inverts a boolean value (true becomes false, and vice-versa).

Code Snippet:

JavaScript


const age = 25;
const hasLicense = true;

// Can this person rent a car?
if (age >= 25 && hasLicense) {
  console.log("Eligible to rent a car.");
}

const isWeekend = true;
const isHoliday = false;

// Time to relax?
if (isWeekend || isHoliday) {
  console.log("Enjoy your day off!");
}