JavaScript tutorials  /  JavaScript Operators
Chapter 3 · JavaScript

JavaScript Operators

JavaScript operators are symbols or keywords that perform specific operations on one or more operands (values or variables). Operators enable developers to manipulate data, make comparisons, perform calculations, and control program flow. They are fundamental building blocks that combine values and variables to produce results.

Think of operators as tools in a toolbox. Just as a hammer drives nails and a saw cuts wood, operators perform different tasks on your data. For example, the '+' operator adds numbers, the '===' operator checks if values are equal, and the '&&' operator checks if multiple conditions are true. Each operator has a specific purpose and helps you write efficient code.

Imagine you're building an e-commerce application. You use arithmetic operators to calculate the total price (price × quantity + tax), comparison operators to verify if a user is old enough for a purchase (age >= 18), logical operators to check if payment is valid AND stock is available, assignment operators to update user data, and bitwise operators for advanced permission systems. These operators work together to create a complete shopping experience, from calculating discounts to validating user permissions.

Operators are essential because they allow you to manipulate data and make decisions in your programs. Without operators, you couldn't perform calculations, compare values, or control program logic. They enable you to write concise, readable code that performs complex operations efficiently. Understanding operators is crucial for every JavaScript developer as they are used in nearly every line of code.

  • Arithmetic Operators: Operators that perform mathematical calculations on numeric values. Include addition (+), subtraction (-), multiplication (*), division (/), modulus (%), and exponentiation (**).
  • Comparison Operators: Operators that compare two values and return a boolean result (true or false). Include == (loose equality), === (strict equality), != (loose inequality), !== (strict inequality), > (greater than), < (less than), >= (greater than or equal), <= (less than or equal).
  • Logical Operators: Operators that combine multiple boolean conditions and return a boolean result. Include && (AND), || (OR), and ! (NOT). Essential for complex conditional statements.
  • Assignment Operators: Operators that assign values to variables and can perform operations simultaneously. Include = (assignment), += (add and assign), -= (subtract and assign), *= (multiply and assign), /= (divide and assign), %= (modulus and assign), **= (exponent and assign).
  • Bitwise Operators: Operators that perform operations on the binary representations of integers. Include & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift), >>> (unsigned right shift). Advanced operators used for low-level data manipulation.
JavaScript operators follow specific syntax patterns depending on their type: Arithmetic: result = operand1 operator operand2 Comparison: if (operand1 operator operand2) { } Logical: if (condition1 operator condition2) { } Assignment: variable operator value Bitwise: result = value1 operator value2
As a developer, you need to perform calculations, make decisions based on conditions, and manipulate data efficiently. Without understanding operators, you would write verbose, inefficient code that's difficult to maintain and prone to errors.
Arithmetic Operators
Performing mathematical operations on numbers using arithmetic operators.
javascript
// Arithmetic Operators let a = 20; let b = 10; console.log('Addition: ' + (a + b)); console.log('Subtraction: ' + (a - b)); console.log('Multiplication: ' + (a * b)); console.log('Division: ' + (a / b)); console.log('Modulus: ' + (a % b)); console.log('Exponentiation: ' + (a ** 2));
Addition: 30 Subtraction: 10 Multiplication: 200 Division: 2 Modulus: 0 Exponentiation: 400
The arithmetic operators perform basic mathematical operations. Addition combines two numbers, subtraction finds the difference, multiplication scales one number by another, division splits one number by another, modulus finds the remainder after division, and exponentiation raises a number to a power.
Comparison Operators
Comparing values to make decisions in your program using comparison operators.
javascript
// Comparison Operators let x = 15; let y = '15'; console.log('x == y (loose equality): ' + (x == y)); console.log('x === y (strict equality): ' + (x === y)); console.log('x != y (loose inequality): ' + (x != y)); console.log('x !== y (strict inequality): ' + (x !== y)); console.log('x > 10: ' + (x > 10)); console.log('x < 20: ' + (x < 20)); console.log('x >= 15: ' + (x >= 15)); console.log('x <= 15: ' + (x <= 15));
x == y (loose equality): true x === y (strict equality): false x != y (loose inequality): false x !== y (strict inequality): true x > 10: true x < 20: true x >= 15: true x <= 15: true
Comparison operators evaluate two values and return a boolean. The loose equality (==) compares values after type coercion, while strict equality (===) compares both value and type. Relational operators (>, <, >=, <=) determine numerical order. Understanding the difference between == and === is critical for avoiding bugs.
Logical Operators
Combining multiple conditions using logical operators to create complex decision logic.
javascript
// Logical Operators let age = 25; let hasLicense = true; let income = 50000; // AND operator (&&) if (age >= 18 && hasLicense) { console.log('You can drive'); } // OR operator (||) if (income > 100000 || age < 30) { console.log('You are eligible for the program'); } // NOT operator (!) if (!hasLicense) { console.log('You need a license'); } else { console.log('You have a valid license'); } // Complex condition if ((age >= 18 && hasLicense) && (income > 30000 || age < 25)) { console.log('Approved for car loan'); }
You can drive You are eligible for the program You have a valid license Approved for car loan
Logical operators combine boolean conditions. AND (&&) returns true only if both conditions are true. OR (||) returns true if at least one condition is true. NOT (!) inverts the boolean value. These operators are essential for creating complex conditional logic in applications.
Assignment Operators
Assigning values to variables and performing calculations simultaneously using assignment operators.
javascript
// Assignment Operators let count = 10; console.log('Initial count: ' + count); count += 5; // count = count + 5 console.log('After += 5: ' + count); count -= 3; // count = count - 3 console.log('After -= 3: ' + count); count *= 2; // count = count * 2 console.log('After *= 2: ' + count); count /= 4; // count = count / 4 console.log('After /= 4: ' + count); count %= 3; // count = count % 3 console.log('After %= 3: ' + count); let power = 2; power **= 3; // power = power ** 3 console.log('After **= 3: ' + power);
Initial count: 10 After += 5: 15 After -= 3: 12 After *= 2: 24 After /= 4: 6 After %= 3: 0 After **= 3: 8
Assignment operators combine assignment with an operation, making code more concise. They modify the variable in place, which is more efficient than writing separate statements. These operators are frequently used in loops and calculations.
Bitwise Operators
Performing operations on binary representations of integers using bitwise operators.
javascript
// Bitwise Operators let num1 = 5; // Binary: 0101 let num2 = 3; // Binary: 0011 console.log('num1 & num2 (AND): ' + (num1 & num2)); // 0001 = 1 console.log('num1 | num2 (OR): ' + (num1 | num2)); // 0111 = 7 console.log('num1 ^ num2 (XOR): ' + (num1 ^ num2)); // 0110 = 6 console.log('~num1 (NOT): ' + (~num1)); // Inverts all bits console.log('num1 << 1 (Left Shift): ' + (num1 << 1)); // 1010 = 10 console.log('num1 >> 1 (Right Shift): ' + (num1 >> 1)); // 0010 = 2 // Practical use: Checking if a bit is set let permissions = 5; // Binary: 0101 (read=1, write=4) console.log('Can read: ' + ((permissions & 1) === 1)); // true console.log('Can write: ' + ((permissions & 4) === 4)); // true console.log('Can execute: ' + ((permissions & 2) === 2));// false
num1 & num2 (AND): 1 num1 | num2 (OR): 7 num1 ^ num2 (XOR): 6 ~num1 (NOT): -6 num1 << 1 (Left Shift): 10 num1 >> 1 (Right Shift): 2 Can read: true Can write: true Can execute: false
Bitwise operators work on the binary representation of numbers. AND returns 1 where both bits are 1, OR returns 1 where at least one bit is 1, XOR returns 1 where bits differ, NOT inverts all bits. Shift operators move bits left or right, effectively multiplying or dividing by powers of 2. These operators are useful for flags and permissions.
  • Using == instead of === for Comparison: A common mistake is using loose equality (==) instead of strict equality (===). Loose equality performs type coercion, which can lead to unexpected results. For example, 5 == '5' returns true, but 5 === '5' returns false. Always use === to avoid type-related bugs.
  • Confusing && and || operators in conditions: Developers often mix up when to use AND (&&) versus OR (||). AND requires ALL conditions to be true, while OR requires only ONE to be true. Misusing these operators can cause logic errors. Example: 'if (age > 18 || hasPermission)' means either condition can be true, while 'if (age > 18 && hasPermission)' means both must be true.
  • Forgetting operator precedence: JavaScript operators have precedence rules. For example, multiplication happens before addition (5 + 3 * 2 = 11, not 16). Forgetting this can cause calculation errors. Use parentheses to make precedence explicit: (5 + 3) * 2 = 16.
  • Misunderstanding the ternary operator behavior: The ternary operator has lower precedence than arithmetic operators. 'let result = 5 + 3 > 6 ? "yes" : "no"' evaluates to 'yes' because 5 + 3 = 8, and 8 > 6 is true. Without understanding precedence, the result may be unexpected.
  • Not using parentheses in complex bitwise operations: Bitwise operations have different precedence than logical operations. (num & 4) === 4 is different from num & 4 === 4. Always use parentheses to ensure correct evaluation order.
  • Attempting to use increment/decrement on non-existent variables: Using ++ or -- on undefined variables creates global variables (in non-strict mode) or throws an error (in strict mode). Always ensure variables are declared before using increment/decrement operators.
  • Always use strict equality (===) instead of loose equality (==): Strict equality (===) compares both value and type without type coercion, making code more predictable and safer. Use === for all comparisons unless you specifically need type coercion. This prevents subtle bugs and makes code easier to understand.
  • Use parentheses to clarify operator precedence: Even though you understand JavaScript precedence, other developers reading your code may not. Use parentheses to make the evaluation order explicit and prevent misunderstandings. For example, write '(a && b) || c' instead of 'a && b || c'.
  • Prefer compound assignment operators for brevity: Use compound assignment operators (+=, -=, *=, etc.) instead of writing out the full operation. Not only is 'count += 5' more concise than 'count = count + 5', it's also more efficient and clearer in intent.
  • Use logical operators for short-circuit evaluation: Take advantage of how && and || work: && stops at the first false value, || stops at the first true value. Use this for efficient code: 'let user = userData || defaultUser' assigns defaultUser if userData is falsy.
  • Avoid complex nested ternary operators: While ternary operators are concise, nesting them makes code unreadable. If you find yourself writing 'a ? b ? c : d : e', use an if-else statement instead. Readability is more important than brevity.
  • Use bitwise operators sparingly and document them: Bitwise operators are powerful but difficult to read. Use them only when necessary (flags, permissions, performance-critical code) and always add comments explaining what they do. Consider using objects or arrays as clearer alternatives.
  • Be aware of operator precedence in your calculations: If you're unsure about precedence, use parentheses. Multiplication/division comes before addition/subtraction, which comes before comparison, which comes before logical operators. When in doubt, be explicit.
What is the difference between == and === in JavaScript?
The == operator (loose equality) compares values after performing type coercion, meaning it attempts to convert operands to the same type before comparison. For example, 5 == '5' returns true. The === operator (strict equality) compares both value and type without any type conversion, so 5 === '5' returns false. Strict equality is preferred in modern JavaScript because it's more predictable and avoids subtle bugs caused by unexpected type coercion.
Easy
Explain operator precedence in JavaScript with an example.
Operator precedence determines the order in which operations are evaluated. For example, in the expression 5 + 3 * 2, multiplication has higher precedence than addition, so it evaluates as 5 + (3 * 2) = 11, not (5 + 3) * 2 = 16. The general order is: exponentiation (**) > multiplication/division/modulus > addition/subtraction > comparison > logical AND > logical OR. You can override precedence with parentheses.
Medium
What is short-circuit evaluation in JavaScript?
Short-circuit evaluation is when JavaScript stops evaluating a logical expression as soon as the result is determined. With && (AND), if the first operand is false, the second operand is not evaluated because the result will be false. With || (OR), if the first operand is true, the second operand is not evaluated because the result will be true. This is useful for efficiency and can prevent errors. Example: 'let user = userData || {}' uses || short-circuit to provide a default value only if userData is falsy.
Medium
What does the nullish coalescing operator (??) do?
The nullish coalescing operator (??) returns the right-hand operand when the left-hand operand is null or undefined. Unlike || which returns the right operand for any falsy value (false, 0, empty string, etc.), ?? only checks for null or undefined. Example: 'let value = 0 ?? 10' returns 0 (not 10), while 'let value = 0 || 10' returns 10. This is useful when you want to provide a default value but distinguish between 'no value' and 'false value'.
Medium
Explain the difference between && and || operators with examples.
The && (AND) operator returns the first falsy value or the last value if all are truthy. Example: 'true && 5 && "hello"' returns 'hello'. The || (OR) operator returns the first truthy value or the last value if all are falsy. Example: 'false || 0 || "hello"' returns 'hello'. These operators don't just return true/false; they return the actual values, which allows for patterns like 'let user = userData || {}' to provide defaults.
Medium
What are bitwise operators and when would you use them?
Bitwise operators perform operations on the binary representations of integers. They include & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift), and >>> (unsigned right shift). Use cases include: setting/checking flags (permissions), performance-critical operations, working with binary data or file formats, and color manipulation (RGB values). Example: Checking if a user has read permission: '(permissions & READ_FLAG) === READ_FLAG'. However, for most applications, simpler alternatives like objects or arrays are preferable for readability.
Hard
What is the difference between ++ and += 1?
Both increment a variable by 1, but ++ is a unary operator that has prefix and postfix variants. The prefix ++count increments before returning the value, while count++ increments after returning the value. The += operator is a compound assignment that modifies the variable. In loops (for (let i = 0; i < 10; i++)), the difference between prefix and postfix rarely matters. However, in assignments like 'let a = count++' vs 'let a = ++count', the return value differs. Generally, use ++ in loops and += when you need the side effect of assignment.
Medium
How does the ternary operator work and what are its limitations?
The ternary operator (? :) is a conditional operator that takes three operands: 'condition ? valueIfTrue : valueIfFalse'. Example: 'let status = age >= 18 ? "adult" : "minor"'. It's more concise than an if-else statement for simple cases. However, nested ternaries become unreadable: 'a ? b ? c : d : e' is confusing and should use if-else instead. The ternary operator should only be used for simple, readable expressions. For complex logic, if-else is clearer.
Easy
What happens when you use arithmetic operators on non-numeric types?
JavaScript performs type coercion. When you add a number and a string, it concatenates them: '5 + "5" = "55"'. With other operators, JavaScript converts operands to numbers: '"10" - "3" = 7', '"10" * "2" = 20', '"10" / "2" = 5'. If the string can't be converted to a number, the result is NaN (Not a Number): '"hello" + 5 = "hello5"', '"hello" - 5 = NaN'. To avoid unexpected results, always ensure operands are of the expected type using typeof or Number() conversion.
Medium
Explain the concept of truthy and falsy values in JavaScript.
In JavaScript, values can be evaluated as true or false in a boolean context. Falsy values (evaluate to false) are: false, 0, -0, 0n (BigInt), "", null, undefined, and NaN. All other values are truthy, including non-zero numbers, non-empty strings, objects, and arrays. Understanding truthy/falsy is crucial for using || and && operators effectively. Example: 'let user = userData || {}' works because an undefined userData is falsy, so the empty object is assigned instead. Be careful: empty arrays [] and empty objects {} are truthy, not falsy.
Medium
Write a program that determines if a person is eligible to vote (age >= 18) AND has registered, using logical operators.
let age = 20; let isRegistered = true; if (age >= 18 && isRegistered) { console.log('You are eligible to vote'); } else { console.log('You are not eligible to vote'); }
Easy
Write a program that calculates the final price of an item after applying a discount and adding tax using arithmetic operators.
let originalPrice = 100; let discountPercent = 20; let taxPercent = 10; let discountAmount = originalPrice * (discountPercent / 100); let priceAfterDiscount = originalPrice - discountAmount; let taxAmount = priceAfterDiscount * (taxPercent / 100); let finalPrice = priceAfterDiscount + taxAmount; console.log('Original Price: $' + originalPrice); console.log('Discount Amount: $' + discountAmount); console.log('Price After Discount: $' + priceAfterDiscount); console.log('Tax: $' + taxAmount); console.log('Final Price: $' + finalPrice);
Easy
Write a program that checks if a number is even or odd using the modulus operator.
let num = 15; if (num % 2 === 0) { console.log(num + ' is even'); } else { console.log(num + ' is odd'); }
Easy
Write a program that assigns default values to variables using the || operator.
function getUserInfo(name, age, city) { let userName = name || 'Anonymous'; let userAge = age || 18; let userCity = city || 'Unknown'; console.log('Name: ' + userName); console.log('Age: ' + userAge); console.log('City: ' + userCity); } getUserInfo('John', 25, 'New York'); getUserInfo('', null, 'London'); getUserInfo();
Medium
Write a program using bitwise operators to check which permissions a user has (read=1, write=2, execute=4).
const READ = 1; const WRITE = 2; const EXECUTE = 4; let userPermissions = READ | WRITE; // Binary: 0011 = 3 console.log('Has read: ' + ((userPermissions & READ) === READ)); console.log('Has write: ' + ((userPermissions & WRITE) === WRITE)); console.log('Has execute: ' + ((userPermissions & EXECUTE) === EXECUTE)); // Grant execute permission userPermissions = userPermissions | EXECUTE; console.log('\nAfter adding execute:'); console.log('Has execute: ' + ((userPermissions & EXECUTE) === EXECUTE));
Hard
Compare == and === by writing code that shows the difference.
let value1 = 5; let value2 = '5'; let value3 = 0; let value4 = false; console.log('5 == "5": ' + (value1 == value2)); // true (type coercion) console.log('5 === "5": ' + (value1 === value2)); // false (different types) console.log('0 == false: ' + (value3 == value4)); // true (type coercion) console.log('0 === false: ' + (value3 === value4)); // false (different types) console.log('null == undefined: ' + (null == undefined)); // true console.log('null === undefined: ' + (null === undefined)); // false
Medium
Write a program that uses ternary operators to categorize ages into groups.
function categorizeAge(age) { let category = age < 13 ? 'Child' : age < 18 ? 'Teenager' : age < 65 ? 'Adult' : 'Senior'; return category; } console.log(categorizeAge(10)); // Child console.log(categorizeAge(15)); // Teenager console.log(categorizeAge(30)); // Adult console.log(categorizeAge(70)); // Senior // Better approach with if-else for clarity: function categorizeAgeIfElse(age) { if (age < 13) return 'Child'; if (age < 18) return 'Teenager'; if (age < 65) return 'Adult'; return 'Senior'; }
Medium
Write a program that uses compound assignment operators to update multiple values.
let score = 100; let level = 1; let multiplier = 2; console.log('Initial - Score: ' + score + ', Level: ' + level); score += 50; // Add bonus points console.log('After bonus - Score: ' + score); score *= multiplier; // Double the score for level-up console.log('After level-up multiplier - Score: ' + score); level += 1; // Increase level console.log('After level-up - Level: ' + level); multiplier **= 2; // Double the multiplier using exponentiation console.log('New multiplier: ' + multiplier);
Easy

JavaScript operators are fundamental tools that enable developers to perform calculations, compare values, make decisions, and manipulate data. Understanding the five main categories—arithmetic (for calculations), comparison (for evaluating conditions), logical (for combining conditions), assignment (for updating variables), and bitwise (for binary operations)—is essential for writing effective code. Key takeaways include: always use === instead of ==, leverage short-circuit evaluation with && and ||, use parentheses to clarify precedence, and employ compound assignment operators for concise code. Mastering operators is a crucial step in becoming a proficient JavaScript developer, as they are used in nearly every program and directly impact code quality, readability, and performance.

© 2026 CompileX. Maintained by Aditya Kumar Sharma.