JavaScript Operators
Learn how JavaScript operators perform calculations, assignments, comparisons, logical decisions, type checks, and other essential operations.
Introduction
JavaScript programs constantly perform operations. Applications calculate prices, compare values, update scores, check permissions, combine conditions, assign data, and make decisions.
Operators are the symbols and keywords that tell JavaScript what operation should be performed on one or more values.
For example, the + operator adds numbers, the === operator compares values and types, the && operator combines conditions, and the = operator stores a value inside a variable.
Operators are fundamental to programming because almost every meaningful expression uses one or more operators.
- What operators are.
- What operands are.
- Why JavaScript programs need operators.
- The major categories of JavaScript operators.
- How arithmetic operators work.
- How addition, subtraction, multiplication, and division work.
- How the remainder operator works.
- How exponentiation works.
- How increment and decrement operators work.
- The difference between prefix and postfix operations.
- How assignment operators work.
- How compound assignment operators simplify code.
- How comparison operators produce boolean results.
- The difference between loose and strict equality.
- How logical operators combine conditions.
- How short-circuit evaluation works.
- How the nullish coalescing operator works.
- The difference between || and ??.
- How unary operators work.
- How typeof and delete work.
- How the ternary operator creates compact decisions.
- How string operators work.
- How optional chaining safely accesses properties.
- What bitwise operators are.
- How operator precedence affects expressions.
- How associativity affects evaluation order.
- How parentheses make expressions predictable.
What is an Operator?
An operator is a symbol or keyword that performs an operation on one or more values.
const firstNumber = 10;const secondNumber = 20;
const result = firstNumber + secondNumber;
console.log(result);Click Run to see what this code prints.
10 + 20│ │ ││ │ └── Operand│ ││ └───── Operator│└──────── OperandIn this expression, 10 and 20 are the values being operated on, while + is the operator that performs addition.
- Operators perform actions on values.
- Values used by operators are called operands.
- Operators can calculate, compare, assign, and evaluate values.
- Some operators use one operand while others use two or three.
Why Do We Need Operators?
Without operators, JavaScript could store values but could not meaningfully process them. Operators allow programs to transform data and make decisions.
Calculations
Add prices, calculate totals, find percentages, and perform mathematical operations.
Assignment
Store values inside variables and update existing values.
Comparison
Compare ages, prices, scores, passwords, and other values.
Decisions
Combine multiple conditions to control application behavior.
Type Checking
Determine the data type of a value using operators such as typeof.
Safe Access
Access nested data safely using modern operators such as optional chaining.
Real-World Analogy
Think of an operator like a machine in a factory. Values enter the machine, the machine performs an operation, and a result comes out.
First Value Operator Second Value 10 + 20 │ │ │ └───────────────┼────────────────┘ ▼ ┌─────────────┐ │ Addition │ │ Machine │ └─────────────┘ │ ▼ 30Different operators act like different machines. The + operator adds values, the > operator compares them, and the && operator combines conditions.
Operands and Operators
The values on which an operator performs an operation are called operands.
const result = 50 - 20;
console.log(result);Click Run to see what this code prints.
50 - 20│ │ ││ │ └── Right Operand│ ││ └───── Operator│└──────── Left OperandOperators can be classified according to the number of operands they use.
1️⃣ Unary Operator
Works with one operand. Example: typeof value or !isLoggedIn.
2️⃣ Binary Operator
Works with two operands. Example: 10 + 20.
3️⃣ Ternary Operator
Works with three parts. Example: condition ? value1 : value2.
Types of JavaScript Operators
JavaScript provides several categories of operators for different programming tasks.
JavaScript Operators │ ├── Arithmetic Operators ├── Assignment Operators ├── Comparison Operators ├── Logical Operators ├── Unary Operators ├── Ternary Operator ├── String Operators ├── Nullish Coalescing ├── Optional Chaining ├── Bitwise Operators └── Type OperatorsArithmetic
Perform mathematical calculations.
Assignment
Assign and update variable values.
Comparison
Compare values and return true or false.
Logical
Combine or reverse conditions.
1️⃣ Unary
Perform operations using a single operand.
Ternary
Choose between two values using a condition.
Arithmetic Operators
Arithmetic operators perform mathematical calculations on numeric values.
Operator Name Example------------------------------------------+ Addition 10 + 5- Subtraction 10 - 5* Multiplication 10 * 5/ Division 10 / 5% Remainder 10 % 3** Exponentiation 2 ** 3++ Increment value++-- Decrement value--const a = 10;const b = 3;
console.log(a + b);console.log(a - b);console.log(a * b);console.log(a / b);console.log(a % b);console.log(a ** b);Click Run to see what this code prints.
Addition Operator (+)
The addition operator adds numeric values.
const firstNumber = 25;const secondNumber = 15;
const total = firstNumber + secondNumber;
console.log(total);Click Run to see what this code prints.
const productPrice = 500;const deliveryCharge = 50;const tax = 90;
const finalPrice = productPrice + deliveryCharge + tax;
console.log(finalPrice);Click Run to see what this code prints.
- Number + Number performs addition.
- String + String performs concatenation.
- A string can cause other values to be converted into strings.
- Convert numeric input before performing calculations.
Subtraction Operator (-)
The subtraction operator subtracts the right operand from the left operand.
const balance = 1000;const purchase = 350;
const remainingBalance = balance - purchase;
console.log(remainingBalance);Click Run to see what this code prints.
Multiplication Operator (*)
The multiplication operator multiplies two numeric values.
const price = 499;const quantity = 3;
const total = price * quantity;
console.log(total);Click Run to see what this code prints.
Division Operator (/)
The division operator divides the left operand by the right operand.
const totalAmount = 1000;const people = 4;
const amountPerPerson = totalAmount / people;
console.log(amountPerPerson);Click Run to see what this code prints.
console.log(10 / 0);console.log(-10 / 0);console.log(0 / 0);Click Run to see what this code prints.
Remainder Operator (%)
The remainder operator returns the remainder left after division.
console.log(10 % 3);console.log(20 % 5);console.log(17 % 4);Click Run to see what this code prints.
The remainder operator is commonly used to determine whether a number is even or odd.
const number = 12;
console.log(number % 2 === 0);Click Run to see what this code prints.
This code is supposed to check whether the number is even, but it uses the wrong operator. Fix it so it correctly prints true for an even number.
12 ÷ 2 = 6 remainder 012 % 2 = 0Even Number
13 ÷ 2 = 6 remainder 113 % 2 = 1Odd NumberExponentiation Operator (**)
The exponentiation operator raises the left operand to the power of the right operand.
console.log(2 ** 3);console.log(5 ** 2);console.log(10 ** 3);Click Run to see what this code prints.
2 ** 3
2 × 2 × 2 │ ▼ 8Increment Operator (++)
The increment operator increases a numeric variable by one.
let score = 10;
score++;
console.log(score);Click Run to see what this code prints.
The increment operation is equivalent to adding one to the current value.
let score = 10;
score = score + 1;
console.log(score);Click Run to see what this code prints.
Decrement Operator (--)
The decrement operator decreases a numeric variable by one.
let lives = 3;
lives--;
console.log(lives);Click Run to see what this code prints.
Prefix vs Postfix
Increment and decrement operators can appear before or after a variable. Their position affects the value returned by the expression.
let number = 5;
const result = number++;
console.log(result);console.log(number);Click Run to see what this code prints.
Postfix returns the original value first and then updates the variable.
let number = 5;
const result = ++number;
console.log(result);console.log(number);Click Run to see what this code prints.
This code should print the updated value both times (11 and 11), but postfix increment logs the old value first. Fix it using the prefix operator so both lines print 11.
Prefix updates the variable first and then returns the updated value.
Postfix: value++
1. Return current value2. Increase value
Prefix: ++value
1. Increase value2. Return new value- Use value++ when you only need to increase a variable.
- Use value-- when you only need to decrease a variable.
- Be careful when using increment or decrement inside larger expressions.
- Separate complex updates into multiple statements for clarity.
Assignment Operators
Assignment operators store values inside variables or update existing variable values.
Operator Example Equivalent---------------------------------------= x = 10 x = 10+= x += 5 x = x + 5-= x -= 5 x = x - 5*= x *= 5 x = x * 5/= x /= 5 x = x / 5%= x %= 5 x = x % 5**= x **= 2 x = x ** 2Basic Assignment Operator (=)
The assignment operator stores the value on its right side inside the variable on its left side.
let score = 100;
console.log(score);Click Run to see what this code prints.
let score = 100;
score = 200;
console.log(score);Click Run to see what this code prints.
- = assigns a value.
- == compares values with coercion.
- === compares values and types strictly.
- Confusing these operators can cause serious logic errors.
Addition Assignment Operator (+=)
The += operator adds a value to the current variable value and stores the result back in the same variable.
let score = 100;
score += 50;
console.log(score);Click Run to see what this code prints.
score += 50
is equivalent to
score = score + 50Other Assignment Operators
let value = 100;
value += 20;console.log(value);
value -= 10;console.log(value);
value *= 2;console.log(value);
value /= 5;console.log(value);
value %= 7;console.log(value);
value **= 2;console.log(value);Click Run to see what this code prints.
Comparison Operators
Comparison operators compare values and return a boolean result: true or false.
Operator Meaning----------------------------------== Equal to=== Strictly equal to!= Not equal to!== Strictly not equal to> Greater than< Less than>= Greater than or equal to<= Less than or equal toconsole.log(10 > 5);console.log(10 < 5);console.log(10 >= 10);console.log(5 <= 10);Click Run to see what this code prints.
Equal Operator (==)
The loose equality operator compares values after allowing type coercion.
console.log(5 == 5);console.log(5 == '5');console.log(0 == false);Click Run to see what this code prints.
- 5 == "5" returns true.
- 0 == false returns true.
- The operands may be converted before comparison.
- This behavior can make code harder to predict.
Strict Equal Operator (===)
The strict equality operator compares both value and data type.
console.log(5 === 5);console.log(5 === '5');console.log(0 === false);Click Run to see what this code prints.
5 == '5'│├── Values compared after coercion└── true
5 === '5'│├── Value: similar├── Type: different└── false- Prefer === for equality comparisons.
- Strict equality avoids unexpected type coercion.
- The code becomes easier to understand.
- Use == only when coercion is intentional and understood.
Not Equal Operators
JavaScript provides loose and strict inequality operators.
console.log(10 != 5);console.log(5 != '5');
console.log(10 !== 5);console.log(5 !== '5');Click Run to see what this code prints.
The !== operator is generally preferred because it compares values without loose equality coercion.
Greater Than and Less Than Operators
const age = 20;
console.log(age > 18);console.log(age < 18);console.log(age >= 20);console.log(age <= 20);Click Run to see what this code prints.
const age = 22;const minimumAge = 18;
const canRegister = age >= minimumAge;
console.log(canRegister);Click Run to see what this code prints.
Logical Operators
Logical operators combine, select, or reverse conditions.
Operator Name---------------------------&& Logical AND|| Logical OR! Logical NOTLogical AND Operator (&&)
The logical AND operator requires both conditions to be truthy for the complete condition to succeed.
const age = 25;const hasLicense = true;
const canDrive = age >= 18 && hasLicense;
console.log(canDrive);Click Run to see what this code prints.
This code should only allow checkout when the user is BOTH logged in AND has items in the cart. Fix the operator so both conditions are required.
Condition A Condition B A && B-------------------------------------true true truetrue false falsefalse true falsefalse false falseLogical OR Operator (||)
The logical OR operator succeeds when at least one condition is truthy.
const isAdmin = false;const isEditor = true;
const canEdit = isAdmin || isEditor;
console.log(canEdit);Click Run to see what this code prints.
Condition A Condition B A || B-------------------------------------true true truetrue false truefalse true truefalse false falseLogical NOT Operator (!)
The logical NOT operator reverses the boolean meaning of a value.
const isLoggedIn = true;
console.log(!isLoggedIn);Click Run to see what this code prints.
console.log(!!'JavaScript');console.log(!!'');console.log(!!100);console.log(!!0);Click Run to see what this code prints.
Using !! converts a value into its boolean equivalent.
Short-Circuit Evaluation
Logical operators do not always evaluate every operand. JavaScript stops as soon as the final result can be determined.
const isLoggedIn = false;
isLoggedIn && console.log('Welcome back!');Click Run to see what this code prints.
Because the first value is false, JavaScript does not evaluate the second operand.
const userName = '';
const displayName = userName || 'Guest';
console.log(displayName);Click Run to see what this code prints.
AND (&&)
false && secondValue │ └── Stop immediately
OR (||)
true || secondValue │ └── Stop immediatelyNullish Coalescing Operator (??)
The nullish coalescing operator returns the right operand only when the left operand is null or undefined.
const userName = null;
const displayName = userName ?? 'Guest';
console.log(displayName);Click Run to see what this code prints.
console.log(0 ?? 100);console.log('' ?? 'Default');console.log(false ?? true);Click Run to see what this code prints.
- null uses the default value.
- undefined uses the default value.
- 0 is preserved.
- false is preserved.
- An empty string is preserved.
Logical OR vs Nullish Coalescing
The || operator uses the right operand for any falsy left value. The ?? operator uses the right operand only for null or undefined.
const quantity = 0;
console.log(quantity || 10);console.log(quantity ?? 10);Click Run to see what this code prints.
The stock count of 0 should be treated as valid (out of stock), not replaced by the default. Fix the operator so it correctly prints 0 instead of the fallback.
value || defaultUses default for:false, 0, '', null, undefined, NaN
value ?? defaultUses default for:null, undefined- Use || when every falsy value should trigger a fallback.
- Use ?? when 0, false, and empty strings are valid values.
- The ?? operator is often safer for configuration and numeric data.
- Choose based on the meaning of your data.
Unary Operators
A unary operator performs an operation using a single operand.
const value = '100';
console.log(typeof value);console.log(+value);console.log(-value);console.log(!value);Click Run to see what this code prints.
Unary Plus and Unary Minus
Unary plus attempts to convert a value into a number. Unary minus converts the value into a number and reverses its sign.
const value = '100';
const result = +value;
console.log(result);console.log(typeof result);Click Run to see what this code prints.
console.log(-10);console.log(-'25');Click Run to see what this code prints.
typeof Operator
The typeof operator returns a string describing the type of a value.
console.log(typeof 'JavaScript');console.log(typeof 100);console.log(typeof true);console.log(typeof undefined);console.log(typeof 10n);console.log(typeof Symbol('id'));console.log(typeof function () {});Click Run to see what this code prints.
console.log(typeof null);Click Run to see what this code prints.
- typeof null returns "object".
- This is a historical JavaScript behavior.
- It does not mean null is a normal object.
- Check null directly when necessary.
delete Operator
The delete operator removes a property from an object.
const user = { name: 'Rahul', age: 25, city: 'Mumbai'};
delete user.city;
console.log(user);Click Run to see what this code prints.
- delete is mainly used for object properties.
- It removes a property from the object.
- It does not delete variables declared with let, const, or var.
- Use it when property removal is actually required.
Ternary Operator
The ternary operator chooses between two values based on a condition. It is the only JavaScript operator with three operands.
condition ? valueIfTrue : valueIfFalseconst age = 20;
const status = age >= 18 ? 'Adult' : 'Minor';
console.log(status);Click Run to see what this code prints.
The branches of this ternary are swapped, so it labels an adult as a Minor. Fix the ternary so it correctly prints 'Adult' for someone who is 20 years old.
age >= 18 │ ┌─────┴─────┐ │ │ true false │ │ ▼ ▼ 'Adult' 'Minor'The ternary operator is useful when a simple condition needs to produce one of two values.
Nested Ternary Operator
A ternary operator can contain another ternary expression, but deeply nested ternaries can become difficult to read.
const score = 85;
const grade = score >= 90 ? 'A' : score >= 75 ? 'B' : score >= 60 ? 'C' : 'Fail';
console.log(grade);Click Run to see what this code prints.
- Simple ternaries are concise and readable.
- Multiple nested levels can become confusing.
- Use if...else when decision logic becomes complex.
- Readability is more important than writing fewer lines.
String Operators
The + operator joins strings together. This operation is called concatenation.
const firstName = 'Rahul';const lastName = 'Sharma';
const fullName = firstName + ' ' + lastName;
console.log(fullName);Click Run to see what this code prints.
let message = 'Hello';
message += ' JavaScript';
console.log(message);Click Run to see what this code prints.
Optional Chaining Operator (?.)
The optional chaining operator safely accesses nested object properties. If a value before ?. is null or undefined, the expression returns undefined instead of causing an error.
const user = { name: 'Rahul'};
// This would cause an error:// console.log(user.address.city);const user = { name: 'Rahul'};
console.log(user.address?.city);Click Run to see what this code prints.
const user = { name: 'Rahul', address: { city: 'Mumbai' }};
console.log(user.address?.city);Click Run to see what this code prints.
const user = { name: 'Rahul'};
const city = user.address?.city ?? 'Unknown';
console.log(city);Click Run to see what this code prints.
- Prevents errors when nested data is missing.
- Reduces repetitive property checks.
- Works well with API response data.
- Can be combined with ?? to provide default values.
Bitwise Operators
Bitwise operators perform operations on the binary representation of integers. They are less common in everyday web development but are useful in low-level operations, flags, graphics, and performance-sensitive systems.
Operator Name-----------------------------& Bitwise AND| Bitwise OR^ Bitwise XOR~ Bitwise NOT<< Left Shift>> Signed Right Shift>>> Unsigned Right Shiftconsole.log(5 & 3);console.log(5 | 3);console.log(5 ^ 3);console.log(5 << 1);console.log(5 >> 1);Click Run to see what this code prints.
5 = 01013 = 0011
Bitwise AND (&)
0101& 0011------ 0001
Result = 1- You do not need bitwise operators for most beginner programs.
- Understand that they operate on binary integer representations.
- They become useful in specialized programming tasks.
- Focus first on arithmetic, comparison, logical, and assignment operators.
Operator Precedence
Operator precedence determines which operation is evaluated first when an expression contains multiple operators.
const result = 10 + 5 * 2;
console.log(result);Click Run to see what this code prints.
This code should add the base price and fee first, then double the total, but operator precedence multiplies the fee before adding. Add parentheses so it correctly prints 30.
Multiplication has higher precedence than addition, so 5 * 2 is evaluated first.
10 + 5 * 2 │ ▼10 + 10 │ ▼ 20Higher Priority │ ▼Parentheses ()Exponentiation **Unary Operators !, +value, -value, typeofMultiplication *, /, %Addition +, -Comparison <, >, <=, >=Equality ==, ===, !=, !==Logical AND &&Logical OR ||Nullish Coalescing ??Ternary ? :Assignment = │ ▼Lower PriorityOperator Associativity
Associativity determines the evaluation direction when operators have the same precedence.
const result = 100 / 10 * 2;
console.log(result);Click Run to see what this code prints.
100 / 10 * 2
100 / 10 │ ▼ 10 * 2 │ ▼ 20Assignment operators are commonly evaluated from right to left.
let a;let b;
a = b = 50;
console.log(a);console.log(b);Click Run to see what this code prints.
Using Parentheses
Parentheses can change evaluation order and make complex expressions easier to understand.
console.log(10 + 5 * 2);Click Run to see what this code prints.
console.log((10 + 5) * 2);Click Run to see what this code prints.
- Parentheses make the intended calculation obvious.
- They can override normal precedence.
- They reduce mistakes in complex expressions.
- Readable expressions are easier to maintain.
Complete Operators Example
The following example combines arithmetic, assignment, comparison, logical, ternary, nullish coalescing, and optional chaining operators in a simple shopping application.
const user = { name: 'Rahul', membership: { type: 'premium' }};
const productPrice = 1200;const quantity = 2;const discountPercent = 10;const deliveryCharge = 100;
const isLoggedIn = true;const hasValidAddress = true;
// Arithmetic operatorsconst subtotal = productPrice * quantity;
const discountAmount = subtotal * (discountPercent / 100);
let finalAmount = subtotal - discountAmount;
// Logical operatorsconst canPlaceOrder = isLoggedIn && hasValidAddress;
// Optional chaining and nullish coalescingconst membershipType = user.membership?.type ?? 'standard';
// Strict comparisonconst isPremium = membershipType === 'premium';
// Ternary operatorconst delivery = isPremium ? 0 : deliveryCharge;
// Assignment operatorfinalAmount += delivery;
// Comparison operatorconst freeDelivery = delivery === 0;
console.log('Customer:', user.name);console.log('Subtotal:', subtotal);console.log('Discount:', discountAmount);console.log('Membership:', membershipType);console.log('Premium User:', isPremium);console.log('Delivery:', delivery);console.log('Free Delivery:', freeDelivery);console.log('Can Place Order:', canPlaceOrder);console.log('Final Amount:', finalAmount);Click Run to see what this code prints.
Product Price × Quantity │ ▼ Subtotal │ ├── Calculate Discount │ ▼ Amount After Discount │ ├── Check Membership │ ├── Determine Delivery │ ▼ Final Amount │ ├── Check Login ├── Check Address │ ▼ Can Place OrderReal-World Applications
Operators are used in almost every JavaScript application.
E-Commerce
Calculate prices, discounts, taxes, quantities, delivery charges, and final totals.
Authentication
Check login status, permissions, roles, and access conditions.
Games
Update scores, lives, levels, health, and movement values.
Forms
Compare input values and combine validation conditions.
Dashboards
Calculate percentages, averages, totals, and comparison results.
APIs
Safely access nested response data and provide fallback values.
Configuration
Use defaults while preserving valid values such as zero and false.
User Interfaces
Choose labels, messages, styles, and states based on conditions.
Common Beginner Mistakes
- Using = when comparison is required.
- Using == when strict equality is intended.
- Forgetting that === compares both value and type.
- Using + with numeric strings and expecting numeric addition.
- Forgetting operator precedence.
- Writing complex expressions without parentheses.
- Confusing % with percentage calculation.
- Assuming division by zero always causes a normal error.
- Confusing prefix and postfix increment.
- Using increment operators inside unnecessarily complex expressions.
- Forgetting that && requires both conditions to succeed.
- Forgetting that || succeeds when at least one condition is truthy.
- Assuming logical operators always return booleans.
- Using || when zero or an empty string is a valid value.
- Using ?? when every falsy value should trigger a default.
- Writing deeply nested ternary expressions.
- Accessing nested properties without checking whether parent properties exist.
- Using optional chaining when missing data should actually cause an error.
- Forgetting that typeof null returns "object".
- Using delete when assigning undefined would better match the application design.
- Using bitwise operators instead of logical operators.
- Ignoring type conversion caused by operators.
- Writing expressions that depend on unclear associativity.
- Performing calculations before converting user input.
- Choosing shorter code over readable code.
// ❌ Assignment instead of comparisonlet value = 10;// if (value = 20) {}
// ❌ Loose equalityconsole.log(5 == '5');
// ❌ String concatenationconsole.log('10' + 20);
// ❌ || replaces valid zeroconsole.log(0 || 100);
// ❌ Confusing precedenceconsole.log(10 + 5 * 2);Click Run to see what this code prints.
Best Practices
- Prefer === instead of ==.
- Prefer !== instead of !=.
- Use descriptive variable names around complex expressions.
- Convert external values before arithmetic operations.
- Use parentheses when evaluation order may not be obvious.
- Keep increment and decrement operations simple.
- Use compound assignment operators when they improve readability.
- Remember that % returns a remainder, not a percentage.
- Use && when every required condition must succeed.
- Use || when at least one condition must succeed.
- Use ! to reverse boolean meaning.
- Use !! only when explicit boolean conversion is useful.
- Use ?? when zero, false, and empty strings are valid values.
- Use || when every falsy value should trigger a fallback.
- Use optional chaining for safely accessing optional nested data.
- Combine ?. with ?? when optional data needs a default value.
- Use ternary operators for simple value selection.
- Use if...else instead of deeply nested ternaries.
- Do not rely on complicated implicit type coercion.
- Understand the difference between arithmetic and string behavior of +.
- Use Number.isNaN() when validating numeric calculations.
- Avoid unnecessary bitwise operators in normal application logic.
- Keep expressions short enough to understand quickly.
- Split complex calculations into meaningful intermediate variables.
- Prioritize clarity over clever operator tricks.
const priceInput = '500';const quantityInput = '2';
const price = Number(priceInput);const quantity = Number(quantityInput);
const hasValidPrice = !Number.isNaN(price) && price >= 0;
const hasValidQuantity = !Number.isNaN(quantity) && quantity > 0;
const canCalculate = hasValidPrice && hasValidQuantity;
const total = canCalculate ? price * quantity : 0;
console.log('Total:', total);Click Run to see what this code prints.
Frequently Asked Questions
An operator is a symbol or keyword that performs an operation on one or more values.
An operand is a value on which an operator performs an operation.
Arithmetic operators perform mathematical calculations such as addition, subtraction, multiplication, and division.
The % operator returns the remainder after division.
No. The % operator calculates a remainder, not a percentage.
The ** operator performs exponentiation and raises one value to the power of another.
The ++ operator increases a numeric variable by one.
The -- operator decreases a numeric variable by one.
value++ returns the old value before incrementing, while ++value increments first and returns the new value.
An assignment operator stores or updates a value in a variable.
It adds a value to the current variable value and stores the result back in the variable.
= assigns a value, while === compares both value and data type.
== allows type coercion, while === compares value and type without loose equality coercion.
Use === for most equality comparisons.
The && operator is logical AND. In boolean conditions, both conditions must succeed.
The || operator is logical OR. In boolean conditions, at least one condition must succeed.
The ! operator reverses the boolean meaning of a value.
Double NOT converts a value into its boolean equivalent.
Short-circuit evaluation means JavaScript stops evaluating a logical expression when the final result can already be determined.
The ?? operator returns a fallback value only when the left operand is null or undefined.
|| uses a fallback for any falsy value, while ?? uses a fallback only for null or undefined.
It preserves valid values such as 0 instead of replacing them with a default.
A unary operator works with one operand.
Unary + attempts to convert a value into a number.
typeof returns a string describing the type of a value.
It is a historical behavior in JavaScript.
The delete operator removes a property from an object.
The ternary operator chooses between two values based on a condition.
The syntax is condition ? valueIfTrue : valueIfFalse.
Small nested ternaries can work, but complex decision logic is usually clearer with if...else.
The optional chaining operator safely accesses properties when parent values may be null or undefined.
The expression returns undefined instead of throwing an error caused by accessing a property of null or undefined.
Yes. Optional chaining can safely access data and ?? can provide a fallback value.
Bitwise operators perform operations on binary integer representations.
Operator precedence determines which operation is evaluated first.
Associativity determines the evaluation direction when operators have the same precedence.
Parentheses make evaluation order explicit and improve readability.
Key Takeaways
- Operators perform operations on values.
- Values used by operators are called operands.
- Unary operators use one operand.
- Binary operators use two operands.
- The ternary operator uses three parts.
- Arithmetic operators perform mathematical calculations.
- + performs addition with numbers.
- + can also perform string concatenation.
- - performs subtraction.
- * performs multiplication.
- / performs division.
- % returns the remainder after division.
- ** performs exponentiation.
- ++ increments a variable by one.
- -- decrements a variable by one.
- Prefix and postfix operations return values differently.
- Assignment operators store and update values.
- Compound assignment operators simplify repeated updates.
- Comparison operators return boolean results.
- == allows type coercion.
- === compares value and type strictly.
- Strict equality is generally preferred.
- && represents logical AND.
- || represents logical OR.
- ! represents logical NOT.
- Logical operators use short-circuit evaluation.
- ?? provides defaults only for null and undefined.
- || provides defaults for any falsy value.
- Unary + can convert values into numbers.
- typeof returns the type description of a value.
- typeof null returns "object" because of historical JavaScript behavior.
- delete removes object properties.
- The ternary operator selects between two values.
- Optional chaining safely accesses optional nested data.
- Bitwise operators work with binary integer representations.
- Operator precedence determines which operation runs first.
- Associativity determines evaluation direction for equal-precedence operators.
- Parentheses can change evaluation order.
- Clear expressions are better than clever but confusing operator combinations.
Summary
Operators are symbols and keywords that allow JavaScript programs to calculate values, assign data, compare information, combine conditions, inspect types, and safely work with application data.
Arithmetic operators perform calculations such as addition, subtraction, multiplication, division, remainder, and exponentiation. Increment and decrement operators update numeric variables by one, while prefix and postfix forms differ in the value returned by the expression.
Assignment operators store and update values. Compound assignment operators such as +=, -=, *=, and /= provide shorter forms for operations that update the same variable.
Comparison operators return boolean results. Loose equality allows type coercion, while strict equality compares both value and type. Strict equality and strict inequality are generally preferred for predictable application logic.
Logical operators combine and reverse conditions. The && and || operators use short-circuit evaluation, while the ! operator reverses boolean meaning. The nullish coalescing operator provides fallback values only for null and undefined, making it useful when values such as zero and false are valid.
Modern JavaScript operators such as optional chaining make it easier to safely access nested data. The ternary operator provides compact value selection, while typeof helps inspect data types.
Operator precedence and associativity determine the order in which complex expressions are evaluated. Parentheses should be used whenever they make the intended order clearer.
- You understand what operators are.
- You understand what operands are.
- You know the major categories of JavaScript operators.
- You can use arithmetic operators.
- You understand addition, subtraction, multiplication, and division.
- You can use the remainder operator.
- You can use exponentiation.
- You understand increment and decrement operators.
- You understand prefix and postfix behavior.
- You can use assignment operators.
- You can use compound assignment operators.
- You can compare values.
- You understand loose and strict equality.
- You can use logical AND, OR, and NOT.
- You understand short-circuit evaluation.
- You can use the nullish coalescing operator.
- You understand the difference between || and ??.
- You understand unary operators.
- You can use typeof.
- You understand the delete operator.
- You can use the ternary operator.
- You can use optional chaining.
- You understand the purpose of bitwise operators.
- You understand operator precedence.
- You understand associativity.
- You know when to use parentheses.
- You are ready to learn JavaScript Input & Output.