Skip to content

JavaScript Operators: The Data Manipulation Toolbox

Operators are like the various tools in a programmer's toolbox—tools for calculating numbers (arithmetic operators), tools for comparing sizes (comparison operators), and tools for making decisions (logical operators). Mastering these tools allows you to flexibly manipulate data and build complex program logic.

Arithmetic Operators

Arithmetic operators perform mathematical calculations, similar to what we learned in elementary school.

Basic Arithmetic Operators

javascript
let a = 10;
let b = 3;

// Addition +
console.log(a + b); // 13

// Subtraction -
console.log(a - b); // 7

// Multiplication *
console.log(a * b); // 30

// Division /
console.log(a / b); // 3.3333333333333335

// Modulo (remainder) %
console.log(a % b); // 1 (10 divided by 3 leaves remainder 1)

// Exponentiation ** (ES7)
console.log(2 ** 3); // 8 (2 to the power of 3)
console.log(5 ** 2); // 25 (5 to the power of 2)

Practical Applications of Modulo Operator

The modulo operator is particularly useful for checking odd/even numbers, circular indexing, and other scenarios:

javascript
// Check for odd/even
function isEven(num) {
  return num % 2 === 0;
}

console.log(isEven(4)); // true
console.log(isEven(7)); // false

// Circular indexing (keep within bounds)
let items = ["apple", "banana", "orange"];
let index = 5;
console.log(items[index % items.length]); // "orange" (5 % 3 = 2)

// Check if a number is a multiple of another
function isMultipleOf(num, divisor) {
  return num % divisor === 0;
}

console.log(isMultipleOf(15, 5)); // true
console.log(isMultipleOf(16, 5)); // false

String Concatenation

The plus sign + becomes a concatenation operator when encountering strings:

javascript
// Number addition
console.log(5 + 3); // 8

// String concatenation
console.log("Hello" + " " + "World"); // "Hello World"

// String with number (number gets converted to string)
console.log("Score: " + 100); // "Score: 100"
console.log("5" + 3); // "53" (not 8!)

// Other operators don't concatenate, they try to convert to numbers
console.log("10" - 5); // 5
console.log("10" * 2); // 20
console.log("10" / 2); // 5

Unary Operators

Unary operators require only one operand:

javascript
// Unary plus + (tries to convert to number)
console.log(+"42"); // 42
console.log(+"3.14"); // 3.14
console.log(+true); // 1
console.log(+false); // 0
console.log(+"hello"); // NaN

// Unary minus - (negates)
console.log(-5); // -5
console.log(-(-5)); // 5
console.log(-"10"); // -10

// Increment ++
let x = 5;
console.log(++x); // 6 (increment then use)
console.log(x); // 6

let y = 5;
console.log(y++); // 5 (use then increment)
console.log(y); // 6

// Decrement --
let a = 10;
console.log(--a); // 9 (decrement then use)
console.log(a); // 9

let b = 10;
console.log(b--); // 10 (use then decrement)
console.log(b); // 9

Assignment Operators

Assignment operators assign values to variables. The basic assignment operator is the equals sign =.

Basic Assignment

javascript
let x = 10; // Assign 10 to x
let y = x; // Assign the value of x to y

console.log(x, y); // 10 10

Compound Assignment Operators

Compound assignment operators combine arithmetic operations with assignment:

javascript
let num = 10;

// Addition assignment +=
num += 5; // Equivalent to num = num + 5
console.log(num); // 15

// Subtraction assignment -=
num -= 3; // Equivalent to num = num - 3
console.log(num); // 12

// Multiplication assignment *=
num *= 2; // Equivalent to num = num * 2
console.log(num); // 24

// Division assignment /=
num /= 4; // Equivalent to num = num / 4
console.log(num); // 6

// Modulo assignment %=
num %= 4; // Equivalent to num = num % 4
console.log(num); // 2

// Exponentiation assignment **=
num **= 3; // Equivalent to num = num ** 3
console.log(num); // 8

Comparison Operators

Comparison operators compare two values and return boolean values (true or false).

Equality Comparison

JavaScript has two sets of equality operators. Understanding their differences is crucial:

javascript
// Equality == (values are equal, allows type coercion)
console.log(5 == 5); // true
console.log(5 == "5"); // true ("5" is converted to number 5)
console.log(0 == false); // true (false is converted to 0)
console.log(null == undefined); // true

// Strict equality === (both value and type must be equal)
console.log(5 === 5); // true
console.log(5 === "5"); // false (different types)
console.log(0 === false); // false (different types)
console.log(null === undefined); // false (different types)

// Inequality != (values are not equal, allows type coercion)
console.log(5 != 3); // true
console.log(5 != "5"); // false ("5" is converted to number 5)

// Strict inequality !== (value or type is not equal)
console.log(5 !== 3); // true
console.log(5 !== "5"); // true (different types)

Best Practice: Always use === and !== to avoid confusion from type coercion.

Size Comparison

javascript
let a = 10;
let b = 5;

// Greater than >
console.log(a > b); // true
console.log(5 > 10); // false

// Less than <
console.log(a < b); // false
console.log(5 < 10); // true

// Greater than or equal >=
console.log(10 >= 10); // true
console.log(10 >= 5); // true
console.log(3 >= 5); // false

// Less than or equal <=
console.log(5 <= 10); // true
console.log(10 <= 10); // true
console.log(15 <= 10); // false

String Comparison

String comparisons follow dictionary order (Unicode encoding):

javascript
console.log("apple" < "banana"); // true
console.log("cat" > "bat"); // true
console.log("a" < "b"); // true

// Note: Uppercase letters have lower Unicode values than lowercase letters
console.log("A" < "a"); // true
console.log("Z" < "a"); // true

// Compare string lengths
let str1 = "hello";
let str2 = "world";
console.log(str1.length === str2.length); // true

Logical Operators

Logical operators combine multiple conditions. There are three main ones: AND (&&), OR (||), and NOT (!).

Logical AND &&

The result is true only when all conditions are true. Like a security door that requires multiple conditions to open.

javascript
// Basic usage
console.log(true && true); // true
console.log(true && false); // false
console.log(false && true); // false
console.log(false && false); // false

// Practical application
let age = 25;
let hasLicense = true;

if (age >= 18 && hasLicense) {
  console.log("You can drive"); // Will execute
}

// Multiple conditions
let score = 85;
let attendance = 90;
let hasProject = true;

if (score >= 80 && attendance >= 85 && hasProject) {
  console.log("You passed with distinction!"); // Will execute
}

Logical OR ||

The result is true if any condition is true. Like having multiple entrances to enter through any one.

javascript
// Basic usage
console.log(true || true); // true
console.log(true || false); // true
console.log(false || true); // true
console.log(false || false); // false

// Practical application
let isWeekend = true;
let isHoliday = false;

if (isWeekend || isHoliday) {
  console.log("You can rest!"); // Will execute
}

// Set default values
function greet(name) {
  name = name || "Guest"; // If no name, use "Guest"
  console.log("Hello, " + name);
}

greet("Alice"); // "Hello, Alice"
greet(); // "Hello, Guest"

Logical NOT !

Negation operation, true becomes false, false becomes true.

javascript
// Basic usage
console.log(!true); // false
console.log(!false); // true

// Double negation
console.log(!!true); // true
console.log(!!0); // false
console.log(!!"hello"); // true (non-empty string is truthy)

// Practical application
let isLoggedIn = false;

if (!isLoggedIn) {
  console.log("Please log in"); // Will execute
}

// Check for empty values
let value = null;
if (!value) {
  console.log("Value is empty"); // Will execute
}

Short-Circuit Evaluation

Logical operators have an important characteristic: short-circuit evaluation.

javascript
// && Short-circuit: if first is falsy, won't evaluate second
let result1 = false && console.log("This won't run");
// console.log won't execute

let result2 = true && console.log("This will run");
// console.log will execute, outputs "This will run"

// || Short-circuit: if first is truthy, won't evaluate second
let result3 = true || console.log("This won't run");
// console.log won't execute

let result4 = false || console.log("This will run");
// console.log will execute, outputs "This will run"

// Practical application: conditional execution
let user = { name: "Emma" };
user && console.log(user.name); // Outputs "Emma"

let noUser = null;
noUser && console.log(noUser.name); // Won't execute (avoids error)

// Practical application: default values
let username = "";
let displayName = username || "Anonymous";
console.log(displayName); // "Anonymous"

Nullish Coalescing Operator ?? (ES2020)

?? returns the right-hand value only when the left side is null or undefined, more precise than ||:

javascript
// || replaces all falsy values
let count = 0;
console.log(count || 10); // 10 (0 is falsy)

// ?? only replaces null/undefined
console.log(count ?? 10); // 0 (count is not null/undefined)

let value = null;
console.log(value ?? "default"); // "default"

let value2 = undefined;
console.log(value2 ?? "default"); // "default"

let value3 = "";
console.log(value3 ?? "default"); // "" (empty string is not null/undefined)

Ternary (Conditional) Operator

The conditional operator is JavaScript's only ternary operator, can simplify if-else statements:

javascript
// Syntax: condition ? valueIfTrue : valueIfFalse

let age = 20;
let canVote = age >= 18 ? "Yes" : "No";
console.log(canVote); // "Yes"

// Equivalent to:
let canVote2;
if (age >= 18) {
  canVote2 = "Yes";
} else {
  canVote2 = "No";
}

// More examples
let score = 85;
let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "D";
console.log(grade); // "B"

// Practical application
function getDiscount(isMember, amount) {
  return isMember ? amount * 0.9 : amount;
}

console.log(getDiscount(true, 100)); // 90
console.log(getDiscount(false, 100)); // 100

typeof Operator

typeof is used to check the type of a value:

javascript
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof Symbol()); // "symbol"
console.log(typeof 123n); // "bigint"
console.log(typeof null); // "object" (historical bug)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function () {}); // "function"

// Practical application
function processValue(value) {
  if (typeof value === "number") {
    return value * 2;
  } else if (typeof value === "string") {
    return value.toUpperCase();
  } else {
    return value;
  }
}

console.log(processValue(5)); // 10
console.log(processValue("hello")); // "HELLO"

Comma Operator

The comma operator evaluates expressions in sequence and returns the value of the last expression:

javascript
let a = (1 + 2, 3 + 4);
console.log(a); // 7 (returns the value of the last expression)

// Usage in for loops
for (let i = 0, j = 10; i < 5; i++, j--) {
  console.log(i, j);
}
// 0 10
// 1 9
// 2 8
// 3 7
// 4 6

Bitwise Operators

Bitwise operators directly manipulate the binary representation of numbers. They offer high performance but are less commonly used:

javascript
// 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)

// Right shift >>
console.log(5 >> 1); // 2 (0101 >> 1 = 0010)

// Unsigned right shift >>>
console.log(-5 >>> 1); // 2147483645

// Practical application: odd/even check (faster)
function isEvenFast(num) {
  return (num & 1) === 0;
}
console.log(isEvenFast(4)); // true
console.log(isEvenFast(7)); // false

delete Operator

delete is used to delete object properties:

javascript
let person = {
  name: "James",
  age: 30,
  city: "Boston",
};

delete person.age;
console.log(person); // { name: "James", city: "Boston" }

// delete doesn't work on variables
let x = 10;
delete x;
console.log(x); // 10 (variables cannot be deleted)

// delete array elements (leaves empty slots)
let arr = [1, 2, 3, 4];
delete arr[1];
console.log(arr); // [1, empty, 3, 4]
console.log(arr.length); // 4 (length doesn't change)

in Operator

in checks if an object has a specific property:

javascript
let car = {
  brand: "Toyota",
  model: "Camry",
  year: 2023,
};

console.log("brand" in car); // true
console.log("color" in car); // false

// Check array indices
let arr = [1, 2, 3];
console.log(0 in arr); // true
console.log(5 in arr); // false

instanceof Operator

instanceof checks if an object is an instance of a specific class:

javascript
let arr = [1, 2, 3];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true

let date = new Date();
console.log(date instanceof Date); // true

function Person(name) {
  this.name = name;
}
let person = new Person("Lily");
console.log(person instanceof Person); // true

Optional Chaining Operator ?. (ES2020)

The optional chaining operator safely accesses nested object properties, avoiding errors:

javascript
let user = {
  name: "Ryan",
  address: {
    city: "Seattle",
  },
};

// Traditional way (verbose)
let city = user && user.address && user.address.city;

// Optional chaining (concise)
let city2 = user?.address?.city;
console.log(city2); // "Seattle"

// Access non-existent properties
let country = user?.address?.country;
console.log(country); // undefined (won't throw error)

// Optional method calls
let result = user?.sayHello?.(); // Calls if method exists

// Optional index access
let arr = [1, 2, 3];
console.log(arr?.[0]); // 1
console.log(arr?.[10]); // undefined

Summary

Operators are the foundational tools of programming. Using them flexibly can make code more concise and efficient.

Key Points Recap:

  • Arithmetic Operators: +, -, *, /, %, ** (exponentiation)
  • Assignment Operators: =, +=, -=, *=, /=, %=, **=
  • Comparison Operators: ==, ===, !=, !==, >, <, >=, <=
  • Logical Operators: &&, ||, !, understand short-circuit evaluation
  • Ternary Operator: ? :, simplifies if-else
  • typeof: Check data types
  • Nullish Coalescing: ??, more precise default value setting
  • Optional Chaining: ?., safe access to nested properties
  • Recommend using === and !== to avoid type coercion
  • Understand operator precedence and associativity (detailed in next section)