JavaScript Operators: A Comprehensive Guide

JavaScript operators are symbols that perform specific operations on one or more values (operands). They are essential for manipulating data and controlling program flow.



Categories of Operators

Arithmetic Operators

Used for mathematical calculations.

  • Examples: +, -, *, /, %, ++, --
  • String concatenation: The + operator can also concatenate strings.

Comparison Operators

Used to compare values and return boolean results (true or false).

  • Examples: ==, ===, !=, !==, >, <, >=, <=

Logical Operators

Used to combine boolean expressions.

  • Examples: && (AND), || (OR), ! (NOT)

Assignment Operators

Assign values to variables.

  • Examples: =, +=, -=, *=, /=

Conditional (Ternary) Operator

A shorthand way to write if-else statements.

Syntax: condition ? expression1 : expression2

Examples

Arithmetic Operators

// Arithmetic operators
let num1 = 10, num2 = 5;
let sum = num1 + num2; // 15
let difference = num1 - num2; // 5
let product = num1 * num2; // 50
let quotient = num1 / num2; // 2
let remainder = num1 % num2; // 0
            
Comparison Operators

// Comparison operators
let isEqual = (num1 == num2); // false
let isNotEqual = (num1 != num2); // true
let isGreaterThan = (num1 > num2); // true
            
Logical Operators

// Logical operators
let isTrue = (num1 > 0 && num2 > 0); // true
let isFalse = (num1 < 0 || num2 < 0); // false
let notTrue = !(num1 === num2); // true
            
Assignment Operators

// Assignment operators
let x = 5;
x += 3; // x is now 8
            
Conditional (Ternary) Operator

// Conditional (ternary) operator
let max = (num1 > num2) ? num1 : num2; // max is 10
            

Operator Precedence

The order in which operators are evaluated is determined by operator precedence. Multiplication and division generally have higher precedence than addition and subtraction. Parentheses can be used to override the default precedence.

Additional Notes

  • The typeof operator: Returns the data type of a value.
  • The delete operator: Removes a property from an object.
  • The in operator: Checks if a property exists in an object.