What are JavaScript Operators? See Examples

JavaScript operators are special symbols used to perform operations on values and variables. Operators can be classified into arithmetic, assignment, comparison, logical, and more. Understanding them is key to writing effective code.


1. Arithmetic Operators

Used for basic mathematical operations:

let x = 10;
let y = 5;

console.log(x + y); // 15 (Addition)
console.log(x - y); // 5  (Subtraction)
console.log(x * y); // 50 (Multiplication)
console.log(x / y); // 2  (Division)
console.log(x % y); // 0  (Modulus - remainder)
console.log(x ** y); // 100000 (Exponentiation)

2. Assignment Operators

Used to assign values to variables:

let a = 10;
a += 5; // a = a + 5 => 15
a -= 3; // a = a - 3 => 12
a *= 2; // a = a * 2 => 24
a /= 4; // a = a / 4 => 6
a %= 4; // a = a % 4 => 2

3. Comparison Operators

Used to compare values and return true or false:

let p = 10;
let q = "10";

console.log(p == q);  // true  (value equality)
console.log(p === q); // false (value + type equality)
console.log(p != q);  // false
console.log(p !== q); // true
console.log(p > 5);   // true
console.log(p < 20);  // true

Tip: Use === and !== instead of == and != to avoid type coercion issues.


4. Logical Operators

Used to combine or invert boolean values:

let isAdult = true;
let hasTicket = false;

console.log(isAdult && hasTicket); // false (AND)
console.log(isAdult || hasTicket); // true  (OR)
console.log(!isAdult);             // false (NOT)

5. Other Operators

  • Ternary Operator: A shorthand for if-else.
let age = 18;
let canVote = age >= 18 ? "Yes" : "No";
console.log(canVote); // "Yes"
  • Typeof Operator: Checks the type of a variable.
console.log(typeof age); // "number"
  • Comma Operator: Allows multiple expressions in one statement.
let x = (1, 2, 3);
console.log(x); // 3

Practical Tips

  • Master arithmetic and logical operators to handle calculations and conditions.
  • Prefer === over == to avoid unexpected type coercion.
  • Use ternary operators for concise conditional assignments.

Understanding operators is essential for every JavaScript developer, as they form the basis for calculations, conditions, and decision-making in code.

Citations:

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *