JavaScript Operators: Complete Guide with Examples
Master all JavaScript operators including arithmetic, comparison, logical, assignment, and more. Learn operator precedence and practical usage patterns.
JavaScript operators are symbols that perform operations on operands (values and variables). Understanding operators is fundamental to writing JavaScript code effectively. This comprehensive guide covers all JavaScript operators with practical examples.
Arithmetic Operators
Arithmetic operators perform mathematical operations on numbers.
Basic Arithmetic
// Addition (+)
console.log(5 + 3); // 8
console.log('Hello' + ' ' + 'World'); // 'Hello World' (string concatenation)
// Subtraction (-)
console.log(10 - 4); // 6
console.log('10' - 4); // 6 (string converted to number)
// Multiplication (*)
console.log(6 * 7); // 42
console.log('6' * '7'); // 42 (strings converted to numbers)
// Division (/)
console.log(20 / 4); // 5
console.log(20 / 3); // 6.666666666666667
// Remainder/Modulo (%)
console.log(10 % 3); // 1
console.log(20 % 4); // 0
console.log(-10 % 3); // -1
// Exponentiation (**)
console.log(2 ** 3); // 8
console.log(4 ** 0.5); // 2 (square root)
console.log(2 ** -1); // 0.5
Increment and Decrement
let x = 5;
// Postfix increment (x++)
console.log(x++); // 5 (returns value, then increments)
console.log(x); // 6
// Prefix increment (++x)
console.log(++x); // 7 (increments, then returns value)
console.log(x); // 7
// Postfix decrement (x--)
console.log(x--); // 7 (returns value, then decrements)
console.log(x); // 6
// Prefix decrement (--x)
console.log(--x); // 5 (decrements, then returns value)
console.log(x); // 5
// Common use cases
let counter = 0;
const arr = [1, 2, 3];
while (counter < arr.length) {
console.log(arr[counter++]); // Use value, then increment
}
Unary Plus and Minus
// Unary plus (+) - converts to number
console.log(+'42'); // 42
console.log(+true); // 1
console.log(+false); // 0
console.log(+null); // 0
console.log(+undefined); // NaN
// Unary minus (-) - negates
console.log(-42); // -42
console.log(-'42'); // -42
console.log(-true); // -1
Assignment Operators
Assignment operators assign values to variables.
Basic Assignment
// Simple assignment (=)
let a = 5;
let b = 'Hello';
let c = true;
// Multiple assignments
let x, y, z;
x = y = z = 10;
console.log(x, y, z); // 10 10 10
// Destructuring assignment
const [first, second] = [1, 2];
const { name, age } = { name: 'John', age: 30 };
Compound Assignment
let num = 10;
// Addition assignment (+=)
num += 5; // num = num + 5
console.log(num); // 15
// Subtraction assignment (-=)
num -= 3; // num = num - 3
console.log(num); // 12
// Multiplication assignment (*=)
num *= 2; // num = num * 2
console.log(num); // 24
// Division assignment (/=)
num /= 4; // num = num / 4
console.log(num); // 6
// Remainder assignment (%=)
num %= 4; // num = num % 4
console.log(num); // 2
// Exponentiation assignment (**=)
num **= 3; // num = num ** 3
console.log(num); // 8
// String concatenation with +=
let str = 'Hello';
str += ' World';
console.log(str); // 'Hello World'
Logical Assignment (ES2021)
// Logical AND assignment (&&=)
let a = 1;
let b = 0;
a &&= 2; // a = a && 2
b &&= 2; // b = b && 2
console.log(a, b); // 2, 0
// Logical OR assignment (||=)
let x = null;
let y = 'existing';
x ||= 'default'; // x = x || 'default'
y ||= 'default'; // y = y || 'default'
console.log(x, y); // 'default', 'existing'
// Nullish coalescing assignment (??=)
let foo = null;
let bar = undefined;
let baz = 'value';
foo ??= 'default'; // foo = foo ?? 'default'
bar ??= 'default'; // bar = bar ?? 'default'
baz ??= 'default'; // baz = baz ?? 'default'
console.log(foo, bar, baz); // 'default', 'default', 'value'
Comparison Operators
Comparison operators compare two values and return a boolean.
Equality Operators
// Equality (==) - type coercion
console.log(5 == 5); // true
console.log(5 == '5'); // true (string converted to number)
console.log(0 == false); // true
console.log(null == undefined); // true
// Inequality (!=)
console.log(5 != 3); // true
console.log(5 != '5'); // false
// Strict equality (===) - no type coercion
console.log(5 === 5); // true
console.log(5 === '5'); // false
console.log(0 === false); // false
console.log(null === undefined); // false
// Strict inequality (!==)
console.log(5 !== '5'); // true
console.log(5 !== 5); // false
// Object comparison
const obj1 = { a: 1 };
const obj2 = { a: 1 };
const obj3 = obj1;
console.log(obj1 === obj2); // false (different objects)
console.log(obj1 === obj3); // true (same reference)
Relational Operators
// Greater than (>)
console.log(5 > 3); // true
console.log('b' > 'a'); // true (lexicographic comparison)
console.log('10' > 9); // true (string converted to number)
// Less than (<)
console.log(3 < 5); // true
console.log('a' < 'b'); // true
// Greater than or equal (>=)
console.log(5 >= 5); // true
console.log(5 >= 3); // true
// Less than or equal (<=)
console.log(3 <= 5); // true
console.log(5 <= 5); // true
// String comparison
console.log('apple' < 'banana'); // true
console.log('Apple' < 'apple'); // true (uppercase comes before)
console.log('10' < '2'); // true (lexicographic, not numeric)
Logical Operators
Logical operators are used with boolean values and expressions.
Basic Logical Operators
// Logical AND (&&)
console.log(true && true); // true
console.log(true && false); // false
console.log(false && true); // false
// Logical OR (||)
console.log(true || false); // true
console.log(false || false); // false
// Logical NOT (!)
console.log(!true); // false
console.log(!false); // true
console.log(!'Hello'); // false
console.log(!''); // true
// Double NOT (!!) - converts to boolean
console.log(!!'Hello'); // true
console.log(!!0); // false
console.log(!!null); // false
console.log(!!{}); // true
Short-Circuit Evaluation
// AND short-circuit
const result1 = false && someFunction(); // someFunction() not called
const result2 = true && 'value'; // 'value'
// OR short-circuit
const result3 = true || someFunction(); // someFunction() not called
const result4 = false || 'default'; // 'default'
// Practical uses
const user = { name: 'John' };
const displayName = user && user.name; // 'John'
const config = null;
const setting = config || { default: true }; // { default: true }
// Chaining
const value = a && b && c && d; // First falsy or last value
const backup = a || b || c || 'default'; // First truthy or last value
Nullish Coalescing (??)
// Nullish coalescing operator (??)
console.log(null ?? 'default'); // 'default'
console.log(undefined ?? 'default'); // 'default'
console.log(0 ?? 'default'); // 0
console.log('' ?? 'default'); // ''
console.log(false ?? 'default'); // false
// Comparison with OR operator
console.log(0 || 'default'); // 'default'
console.log(0 ?? 'default'); // 0
// Practical example
function getConfig(userConfig) {
const config = {
timeout: userConfig.timeout ?? 3000,
retries: userConfig.retries ?? 3,
debug: userConfig.debug ?? false,
};
return config;
}
Bitwise Operators
Bitwise operators work on 32-bit binary representations of numbers.
// Bitwise AND (&)
console.log(5 & 3); // 1 (0101 & 0011 = 0001)
// Bitwise OR (|)
console.log(5 | 3); // 7 (0101 | 0011 = 0111)
// Bitwise XOR (^)
console.log(5 ^ 3); // 6 (0101 ^ 0011 = 0110)
// Bitwise NOT (~)
console.log(~5); // -6 (inverts all bits)
// Left shift (<<)
console.log(5 << 1); // 10 (0101 << 1 = 1010)
console.log(5 << 2); // 20 (0101 << 2 = 10100)
// Sign-propagating right shift (>>)
console.log(10 >> 1); // 5 (1010 >> 1 = 0101)
console.log(-10 >> 1); // -5 (preserves sign)
// Zero-fill right shift (>>>)
console.log(10 >>> 1); // 5
console.log(-10 >>> 1); // 2147483643 (fills with zeros)
// Practical uses
// Check if number is even/odd
const isEven = (n) => (n & 1) === 0;
console.log(isEven(4)); // true
console.log(isEven(5)); // false
// Toggle flags
let flags = 0b0000;
const FLAG_A = 0b0001;
const FLAG_B = 0b0010;
flags |= FLAG_A; // Set flag A
flags &= ~FLAG_B; // Clear flag B
Special Operators
Conditional (Ternary) Operator
// Syntax: condition ? trueValue : falseValue
const age = 18;
const status = age >= 18 ? 'adult' : 'minor';
console.log(status); // 'adult'
// Nested ternary (use sparingly)
const score = 85;
const grade =
score >= 90
? 'A'
: score >= 80
? 'B'
: score >= 70
? 'C'
: score >= 60
? 'D'
: 'F';
console.log(grade); // 'B'
// With functions
const greeting = (time) =>
time < 12 ? 'Good morning' : time < 18 ? 'Good afternoon' : 'Good evening';
Comma Operator
// Evaluates expressions left to right, returns last
let x = (1, 2, 3);
console.log(x); // 3
// In for loops
for (let i = 0, j = 10; i < j; i++, j--) {
console.log(i, j);
}
// Return multiple values (rare use)
const func = () => (console.log('side effect'), 'return value');
console.log(func()); // 'return value' (after logging)
typeof Operator
console.log(typeof 42); // 'number'
console.log(typeof 'Hello'); // 'string'
console.log(typeof true); // 'boolean'
console.log(typeof undefined); // 'undefined'
console.log(typeof null); // 'object' (historic bug)
console.log(typeof {}); // 'object'
console.log(typeof []); // 'object'
console.log(typeof function () {}); // 'function'
console.log(typeof Symbol()); // 'symbol'
console.log(typeof 42n); // 'bigint'
// Checking existence
if (typeof someVariable !== 'undefined') {
// Variable exists
}
instanceof Operator
class Animal {}
class Dog extends Animal {}
const myDog = new Dog();
console.log(myDog instanceof Dog); // true
console.log(myDog instanceof Animal); // true
console.log(myDog instanceof Object); // true
console.log([] instanceof Array); // true
console.log([] instanceof Object); // true
console.log({} instanceof Object); // true
console.log(new Date() instanceof Date); // true
// Custom instanceof behavior
class MyClass {
static [Symbol.hasInstance](instance) {
return instance.customProperty === true;
}
}
const obj = { customProperty: true };
console.log(obj instanceof MyClass); // true
in Operator
const person = { name: 'John', age: 30 };
console.log('name' in person); // true
console.log('height' in person); // false
console.log('toString' in person); // true (inherited)
// With arrays
const arr = ['a', 'b', 'c'];
console.log(0 in arr); // true
console.log(3 in arr); // false
console.log('length' in arr); // true
// Checking before access
if ('property' in object) {
console.log(object.property);
}
delete Operator
const obj = { a: 1, b: 2, c: 3 };
delete obj.b;
console.log(obj); // { a: 1, c: 3 }
// Delete array element (creates hole)
const arr = [1, 2, 3, 4];
delete arr[2];
console.log(arr); // [1, 2, empty, 4]
console.log(arr.length); // 4 (length unchanged)
// Cannot delete variables
let x = 5;
delete x; // false in strict mode
console.log(x); // 5
// Cannot delete non-configurable properties
delete Math.PI; // false
void Operator
// Evaluates expression and returns undefined
console.log(void 0); // undefined
console.log(void 0); // undefined
// Common use: javascript: URLs
// <a href="javascript:void(0)">Click me</a>
// Ensuring undefined
const undefined = 'not undefined'; // Bad practice!
console.log(void 0 === undefined); // false
Operator Precedence
Understanding operator precedence is crucial for writing correct expressions.
// Precedence examples
console.log(2 + 3 * 4); // 14 (not 20)
console.log((2 + 3) * 4); // 20
console.log(true || (false && false)); // true (AND has higher precedence)
console.log((true || false) && false); // false
// Assignment has low precedence
let a, b;
a = b = 5; // Right-to-left associativity
console.log(a, b); // 5, 5
// Comparison vs logical
console.log(1 < 2 && 2 < 3); // true
console.log(1 < 2 < 3); // true (but not what you think!)
// 1 < 2 = true, true < 3 = 1 < 3 = true
// Use parentheses for clarity
const result = (a && b) || (c && d);
Optional Chaining (?.)
const user = {
name: 'John',
address: {
street: '123 Main St',
},
};
// Safe property access
console.log(user?.name); // 'John'
console.log(user?.phone?.number); // undefined (no error)
// Method calls
console.log(user.getName?.()); // undefined (no error)
// Array access
const arr = null;
console.log(arr?.[0]); // undefined (no error)
// Dynamic property access
const prop = 'name';
console.log(user?.[prop]); // 'John'
// Combining with nullish coalescing
const phone = user?.phone?.number ?? 'No phone';
console.log(phone); // 'No phone'
Best Practices
- Use strict equality (===) instead of loose equality (==)
- Parenthesize complex expressions for clarity
- Avoid nested ternary operators - use if/else for readability
- Understand truthy/falsy values when using logical operators
- Be careful with operator precedence - use parentheses when in doubt
- Use optional chaining for safe property access
- Prefer nullish coalescing (??) over OR (||) for default values
Conclusion
JavaScript operators are the building blocks of expressions and logic in your code. Understanding how each operator works, including their precedence and special behaviors, is essential for writing correct and efficient JavaScript. Practice using these operators in different contexts to become proficient in JavaScript programming.