JavaScript Operators

JavaScript operators are symbols that perform operations on variables and values. They are the building blocks for calculations, comparisons, logic, and more. Understanding operators is essential for writing functional JavaScript code.

Operator Types

JavaScript provides several categories of operators, each serving different purposes. Operators are symbols (like +, -, *, ==) or keywords (like typeof, instanceof) that tell JavaScript to perform specific operations on one or more values (called operands). Understanding the different types and how they work is fundamental to programming.

Arithmetic operators perform mathematical calculations on numbers. These include addition (+), subtraction (-), multiplication (*), division (/), modulus (% for remainder), exponentiation (** for powers), and increment/decrement (++ and --). Arithmetic operators are used for calculations, counters, and mathematical operations throughout your code.

Assignment operators assign values to variables. The simple assignment operator (=) assigns a value, while compound assignment operators (+= , -=, *=, /=, etc.) combine an operation with assignment as shorthand. For example, x += 5 is shorthand for x = x + 5. These operators make code more concise and readable.

Comparison operators compare two values and return a boolean (true or false). These include equal (==), strict equal (===), not equal (!=), strict not equal (!==), greater than (>), less than (<), greater than or equal (>=), and less than or equal (<=). Comparison operators are used in conditional statements to make decisions in your code.

Logical operators combine or invert boolean values. The AND operator (&&) returns true only if both operands are true. The OR operator (||) returns true if at least one operand is true. The NOT operator (!) inverts a boolean value. Logical operators are essential for complex conditional logic and control flow.

Type operators provide information about data types. The typeof operator returns a string indicating the type of a value ("number", "string", "object", etc.). The instanceof operator tests whether an object is an instance of a specific class or constructor. These operators are useful for type checking and validation.

// Arithmetic
let x = 5;
let y = 2;
let sum = x + y;      // 7
let diff = x - y;     // 3
let product = x * y;  // 10
let quotient = x / y; // 2.5
let remainder = x % y; // 1

// Increment/Decrement
let count = 0;
count++;  // 1
count--;  // 0

// Assignment
let a = 10;
a += 5;  // a = a + 5 = 15
a -= 3;  // a = a - 3 = 12
a *= 2;  // a = a * 2 = 24