Skip to main content

Command Palette

Search for a command to run...

JavaScript Mastery - Operators

Exploring JavaScript: Arithmetic, Logical, Assignment, Comparison, and Bitwise Operators Explained

Updated
14 min read
JavaScript Mastery - Operators
C

At Code Subtle, we empower aspiring web developers through personalized mentorship and engaging learning resources. Our community bridges the gap between theory and practice, guiding students from basics to advanced concepts. We offer expert mentorship and write interactive, user-friendly articles on all aspects of web development. Join us to learn, grow, and build your future in tech!

Introduction to JavaScript Operators

Operators in JavaScript are special symbols that perform operations on operands (values and variables). They form the foundation of any programming language by allowing us to manipulate data, compare values, and create logical flows in our applications. JavaScript provides numerous operators that help developers create dynamic and interactive web applications.

Arithmetic Operators

Arithmetic operators perform mathematical calculations on numeric values, allowing us to implement everything from simple calculations to complex mathematical algorithms.

Addition (+)

The addition operator adds two values together and is commonly used in calculations, string concatenation, and incrementing variables.

// Example 1: Adding numbers
let total = 10 + 5;
console.log(total); // Output: 15

// Example 2: String concatenation
let firstName = "Code";
let lastName = "Subtle";
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: "Code Subtle"

// Example 3: Mixed types
let mixedResult = 42 + "3";
console.log(mixedResult); // Output: "423" (Number converts to string)

Subtraction (-)

The subtraction operator subtracts the right operand from the left operand and is primarily used in mathematical operations.

// Example 1: Basic subtraction
let difference = 20 - 5;
console.log(difference); // Output: 15

// Example 2: Negative results
let negativeResult = 10 - 25;
console.log(negativeResult); // Output: -15

// Example 3: With variables
let stock = 100;
let sold = 42;
let remaining = stock - sold;
console.log(remaining); // Output: 58

Multiplication (*)

The multiplication operator multiplies two values together and is essential for scaling values and performing mathematical computations.

// Example 1: Basic multiplication
let product = 4 * 5;
console.log(product); // Output: 20

// Example 2: Calculating area
let length = 10;
let width = 5;
let area = length * width;
console.log(area); // Output: 50

// Example 3: Calculating total cost
let price = 2.99;
let quantity = 7;
let totalCost = price * quantity;
console.log(totalCost); // Output: 20.93

Division (/)

The division operator divides the left operand by the right operand and is used in calculations requiring proportional values or ratios.

// Example 1: Basic division
let quotient = 20 / 4;
console.log(quotient); // Output: 5

// Example 2: Non-integer result
let nonInteger = 10 / 3;
console.log(nonInteger); // Output: 3.3333333333333335

// Example 3: Division by zero
let infinityResult = 5 / 0;
console.log(infinityResult); // Output: Infinity

Modulus (%)

The modulus operator returns the remainder after division and is particularly useful for cycling through ranges, checking if numbers are even or odd, and pagination.

// Example 1: Basic remainder
let remainder = 17 % 5;
console.log(remainder); // Output: 2

// Example 2: Checking for even/odd
let number = 42;
let isEven = number % 2 === 0;
console.log(isEven); // Output: true

// Example 3: Cycling through a range
for (let i = 0; i < 10; i++) {
    let position = i % 3;
    console.log(position); // Outputs: 0, 1, 2, 0, 1, 2, 0, 1, 2, 0
}

Exponentiation (**)

The exponentiation operator raises the left operand to the power of the right operand and is used in mathematical calculations, geometric scaling, and compound interest calculations.

// Example 1: Basic exponentiation
let squared = 5 ** 2;
console.log(squared); // Output: 25

// Example 2: Cubic value
let volume = 3 ** 3;
console.log(volume); // Output: 27

// Example 3: Fractional exponents
let squareRoot = 16 ** 0.5;
console.log(squareRoot); // Output: 4

Tips for Arithmetic Operators:

  1. Be aware of type coercion, especially with the + operator which can concatenate strings.

  2. For precise financial calculations, use libraries like Decimal.js to avoid floating-point precision issues.

  3. Use parentheses to clarify the order of operations when combining multiple arithmetic operations.

Assignment Operators

Assignment operators assign values to JavaScript variables and provide shortcuts for combining operations with assignments.

Basic Assignment (=)

The basic assignment operator assigns a value to a variable and is the foundation of variable manipulation in JavaScript.

// Example 1: Assigning a value
let count = 10;
console.log(count); // Output: 10

// Example 2: Chaining assignments
let a, b, c;
a = b = c = 5;
console.log(a, b, c); // Output: 5 5 5

// Example 3: Assigning an expression result
let x = 5;
let y = 3;
let result = x + y;
console.log(result); // Output: 8

Addition Assignment (+=)

The addition assignment operator adds the right operand to the left operand and assigns the result to the left operand, providing a convenient way to increment values or append strings.

// Example 1: Incrementing a number
let score = 10;
score += 5; // Equivalent to: score = score + 5
console.log(score); // Output: 15

// Example 2: String concatenation
let message = "Hello";
message += " World";
console.log(message); // Output: "Hello World"

// Example 3: In a loop
let sum = 0;
for (let i = 1; i <= 5; i++) {
    sum += i;
}
console.log(sum); // Output: 15 (1+2+3+4+5)

Subtraction Assignment (-=)

The subtraction assignment operator subtracts the right operand from the left operand and assigns the result to the left operand, useful for decrementing values or tracking remaining amounts.

// Example 1: Decrementing a value
let budget = 1000;
budget -= 250;
console.log(budget); // Output: 750

// Example 2: Multiple operations
let counter = 20;
counter -= 5;
counter -= 3;
console.log(counter); // Output: 12

// Example 3: In a countdown
let countdown = 10;
while (countdown > 0) {
    console.log(countdown);
    countdown -= 1;
}
// Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

Multiplication Assignment (*=)

The multiplication assignment operator multiplies the left operand by the right operand and assigns the result to the left operand, useful for scaling values or compound calculations.

// Example 1: Scaling a value
let factor = 2;
factor *= 5;
console.log(factor); // Output: 10

// Example 2: Compound interest
let principal = 1000;
let interestRate = 1.05; // 5% interest
// After 3 years
principal *= interestRate;
principal *= interestRate;
principal *= interestRate;
console.log(principal); // Output: approximately 1157.63

// Example 3: Calculating factorial
let factorial = 1;
for (let i = 1; i <= 5; i++) {
    factorial *= i;
}
console.log(factorial); // Output: 120 (1*2*3*4*5)

Division Assignment (/=)

The division assignment operator divides the left operand by the right operand and assigns the result to the left operand, useful for ratio calculations or proportional scaling.

// Example 1: Reducing a value
let quantity = 100;
quantity /= 2;
console.log(quantity); // Output: 50

// Example 2: Sequential division
let number = 64;
number /= 2; // 32
number /= 2; // 16
console.log(number); // Output: 16

// Example 3: Percentage calculation
let totalScore = 850;
let maxPossible = 1000;
let percentage = totalScore;
percentage /= maxPossible;
percentage *= 100;
console.log(percentage); // Output: 85

Modulus Assignment (%=)

The modulus assignment operator takes the modulus of the left operand by the right operand and assigns the result to the left operand, useful for cyclic operations or range limiting.

// Example 1: Keeping a value within range
let position = 7;
position %= 5; // Ensures position is between 0 and 4
console.log(position); // Output: 2

// Example 2: Clock hours
let hours = 25;
hours %= 12;
console.log(hours); // Output: 1

// Example 3: Rotating through options
let options = ["Red", "Green", "Blue", "Yellow"];
let selection = 0;
// After multiple selections
selection += 6; // User moved 6 positions
selection %= options.length;
console.log(options[selection]); // Output: "Green" (6 % 4 = 2)

Tips for Assignment Operators:

  1. Use compound assignment operators to make your code more concise and readable.

  2. Remember that each compound assignment operator has a non-compound equivalent (e.g., x += 5 is the same as x = x + 5).

  3. Be careful with assignment in conditionals as it can lead to bugs; use comparison operators instead.

Comparison Operators

Comparison operators compare two values and return a boolean result, essential for conditional logic and decision-making in applications.

Equality (==)

The equality operator compares two values for equality after converting them to a common type, useful when comparing values where type isn't critical.

// Example 1: Comparing numbers
let a = 5;
let b = 5;
console.log(a == b); // Output: true

// Example 2: Type coercion
let num = 10;
let str = "10";
console.log(num == str); // Output: true

// Example 3: Different types
console.log(0 == false); // Output: true
console.log("" == 0); // Output: true

Strict Equality (===)

The strict equality operator compares two values for equality without type conversion, preferred in most cases for its predictability and safety.

// Example 1: Same type and value
let x = 42;
let y = 42;
console.log(x === y); // Output: true

// Example 2: Different types
let number = 5;
let string = "5";
console.log(number === string); // Output: false

// Example 3: With booleans
console.log(0 === false); // Output: false
console.log(true === 1); // Output: false

Inequality (!=)

The inequality operator checks if two values are not equal after type conversion, useful for negative conditions where type isn't critical.

// Example 1: Different values
let c = 10;
let d = 5;
console.log(c != d); // Output: true

// Example 2: With type coercion
let value = 0;
let empty = "";
console.log(value != empty); // Output: false (both convert to falsy)

// Example 3: With objects
let obj1 = {name: "Code"};
let obj2 = {name: "Code"};
console.log(obj1 != obj2); // Output: true (different references)

Strict Inequality (!==)

The strict inequality operator checks if two values are not equal without type conversion, providing safer comparisons in most situations.

// Example 1: Different types
let num = 0;
let bool = false;
console.log(num !== bool); // Output: true

// Example 2: Same value, different types
let number = 42;
let string = "42";
console.log(number !== string); // Output: true

// Example 3: With null and undefined
console.log(null !== undefined); // Output: true

Greater Than (>)

The greater than operator checks if the left operand is greater than the right operand, useful for range checking and sorting operations.

// Example 1: Comparing numbers
let price1 = 100;
let price2 = 80;
console.log(price1 > price2); // Output: true

// Example 2: With strings (lexicographical comparison)
console.log("banana" > "apple"); // Output: true (b comes after a)

// Example 3: Age verification
let userAge = 21;
let minimumAge = 18;
let canAccess = userAge > minimumAge;
console.log(canAccess); // Output: true

Less Than (<)

The less than operator checks if the left operand is less than the right operand, useful for threshold checking and sorting.

// Example 1: Basic comparison
let temperature = 15;
let freezingPoint = 32;
console.log(temperature < freezingPoint); // Output: true

// Example 2: String comparison
console.log("apple" < "banana"); // Output: true

// Example 3: Checking if under budget
let cost = 45.99;
let budget = 50;
let isAffordable = cost < budget;
console.log(isAffordable); // Output: true

Greater Than or Equal (>=)

The greater than or equal operator checks if the left operand is greater than or equal to the right operand, useful for minimum threshold validations.

// Example 1: Minimum requirement
let score = 75;
let passingScore = 70;
console.log(score >= passingScore); // Output: true

// Example 2: Equal values
let a = 10;
let b = 10;
console.log(a >= b); // Output: true

// Example 3: Date comparison
let currentYear = 2023;
let targetYear = 2020;
let isFutureOrPresent = currentYear >= targetYear;
console.log(isFutureOrPresent); // Output: true

Less Than or Equal (<=)

The less than or equal operator checks if the left operand is less than or equal to the right operand, useful for maximum threshold validations.

// Example 1: Maximum limit
let items = 5;
let maxItems = 10;
console.log(items <= maxItems); // Output: true

// Example 2: Equal values
let x = 42;
let y = 42;
console.log(x <= y); // Output: true

// Example 3: Weight limit
let bagWeight = 49.5;
let weightLimit = 50;
let isWithinLimit = bagWeight <= weightLimit;
console.log(isWithinLimit); // Output: true

Tips for Comparison Operators:

  1. Use strict equality (===) and strict inequality (!==) by default to avoid unexpected type coercion issues.

  2. Remember that comparing objects checks references, not content equality.

  3. When comparing strings, be aware that the comparison is case-sensitive and based on Unicode values.

Logical Operators

Logical operators perform logical operations on boolean values and are essential for combining multiple conditions in control structures.

Logical AND (&&)

The logical AND operator returns true if both operands are true, otherwise returns false. It's used to ensure multiple conditions are met.

// Example 1: Multiple conditions
let isAdult = true;
let hasID = true;
let canEnter = isAdult && hasID;
console.log(canEnter); // Output: true

// Example 2: With expressions
let age = 25;
let subscription = "premium";
let canAccessContent = age >= 18 && subscription === "premium";
console.log(canAccessContent); // Output: true

// Example 3: Short-circuit evaluation
let user = {name: "Code Subtle"};
let isActive = user && user.isActive;
console.log(isActive); // Output: undefined (right side evaluated only if left is truthy)

Logical OR (||)

The logical OR operator returns true if at least one operand is true, otherwise returns false. It's used for fallbacks or alternative conditions.

// Example 1: Alternative conditions
let isAdmin = false;
let isModerator = true;
let canDeletePost = isAdmin || isModerator;
console.log(canDeletePost); // Output: true

// Example 2: Default values
let username = "";
let defaultName = "Guest";
let displayName = username || defaultName;
console.log(displayName); // Output: "Guest" (first truthy value)

// Example 3: Multiple fallbacks
let userInput = null;
let savedData = undefined;
let defaultValue = "New User";
let result = userInput || savedData || defaultValue;
console.log(result); // Output: "New User"

Logical NOT (!)

The logical NOT operator returns the opposite boolean value of its operand, useful for negating conditions or checking for non-existence.

// Example 1: Negating a condition
let isLoggedIn = false;
let showLoginForm = !isLoggedIn;
console.log(showLoginForm); // Output: true

// Example 2: Checking for emptiness
let array = [];
let isEmpty = !array.length;
console.log(isEmpty); // Output: true

// Example 3: Double negation (for boolean conversion)
let value = "Hello";
let isTruthy = !!value;
console.log(isTruthy); // Output: true

Nullish Coalescing (??)

The nullish coalescing operator returns the right-hand operand when the left operand is null or undefined, providing a way to handle missing values without treating other falsy values as missing.

// Example 1: Default for null/undefined
let userSettings = null;
let defaultSettings = {theme: "dark"};
let settings = userSettings ?? defaultSettings;
console.log(settings); // Output: {theme: "dark"}

// Example 2: Comparison with ||
let count = 0;
let fallback = 10;
let result1 = count ?? fallback; // 0 is a valid value
let result2 = count || fallback; // 0 is falsy
console.log(result1); // Output: 0
console.log(result2); // Output: 10

// Example 3: Nested nullish coalescing
let config = {
    api: {
        timeout: null
    }
};
let timeout = config.api.timeout ?? 30000;
console.log(timeout); // Output: 30000

Tips for Logical Operators:

  1. Use short-circuit evaluation with && and || for conditional execution or default values.

  2. Remember that logical operators in JavaScript don't always return boolean values – they return the actual value that determined the result.

  3. Use nullish coalescing (??) instead of || when you need to distinguish between null/undefined and other falsy values.

Ternary Operator

The ternary (conditional) operator is a shorthand for the if-else statement, providing a concise way to select one of two values based on a condition.

// Example 1: Basic usage
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // Output: "Adult"

// Example 2: With expressions
let score = 85;
let result = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
console.log(result); // Output: "B"

// Example 3: In a template literal
let isLoggedIn = true;
let greeting = `Welcome ${isLoggedIn ? "back" : "guest"}!`;
console.log(greeting); // Output: "Welcome back!"

Tips for Ternary Operator:

  1. Use the ternary operator for simple, concise conditional assignments.

  2. Avoid nesting too many ternary operators as it can reduce readability.

  3. Consider using parentheses to make complex ternary operations clearer.

Increment and Decrement Operators

The increment (++) and decrement (--) operators are among JavaScript's most fundamental yet nuanced tools. These unary operators provide elegant shortcuts for modifying numeric values, but their behavior varies significantly depending on their placement—a subtlety that separates novice developers from seasoned professionals.

Understanding Pre and Post Operations

JavaScript offers two distinct forms of these operators: prefix (pre-increment/decrement) and postfix (post-increment/decrement). The distinction lies not just in syntax, but in when the operation occurs and what value gets returned.

Prefix operators (++variable, --variable) modify the value first, then return the new value.

Postfix operators (variable++, variable--) return the current value first, then perform the modification.

Practical Examples

Example 1:

let score = 10;

console.log(++score);  // 11 (increments first, then returns)
console.log(score++);  // 11 (returns current, then increments)
console.log(score);    // 12 (now reflects the post-increment)

Example 2:

// Nested Expression with Increment & Decrement
let x = 3, y = 5;
let result = x++ + --y + x;
console.log(result); 
// 3 + 4 + 4 = 11

Example 3:

let a = 5;
console.log(a++); // 5 (prints before incrementing)
console.log(a);   // 6

let b = 5;
console.log(++b); // 6 (increments first, then prints)
Example 4: Array Manipulation

Tips and Best Practices

Choose prefix for pure modification. When you only need to change a value without using the original, prefix operators are more semantically clear and potentially more performant in certain JavaScript engines.

Leverage postfix for state capture. Use postfix when you need both the original value and the side effect of modification, particularly in loops and conditional statements.

When to Use Each Form

Prefix (++var) excels in scenarios where you need the modified value immediately: incrementing before comparison, updating counters at the start of operations, or when the return value will be used in calculations.

Postfix (var++) shines when you need the current value but want the side effect of modification: classic for-loop incrementing, accessing array elements while moving the index, or capturing state before changing it.

JavaScript Mastery GitHub : JavaScript Core Concepts in Details

JavaScript Mastery

Part 2 of 10

In this article by Code Subtle, we are making an in-depth dive into the JavaScript Programming Language and explaining every topic in detail with definitions, syntax, and examples. We will also give interview questions in the end of the article

Up next

JavaScript Mastery - Conditional Statements

Full Overview of JavaScript Control Statements, Truthy and falsy values