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);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);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);Addition Operator (+)
The addition operator adds numeric values.
const firstNumber = 25;
const secondNumber = 15;
const total = firstNumber + secondNumber;
console.log(total);const productPrice = 500;
const deliveryCharge = 50;
const tax = 90;
const finalPrice = productPrice + deliveryCharge + tax;
console.log(finalPrice);- 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);Multiplication Operator (*)
The multiplication operator multiplies two numeric values.
const price = 499;
const quantity = 3;
const total = price * quantity;
console.log(total);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);console.log(10 / 0);
console.log(-10 / 0);
console.log(0 / 0);Remainder Operator (%)
The remainder operator returns the remainder left after division.
console.log(10 % 3);
console.log(20 % 5);
console.log(17 % 4);The remainder operator is commonly used to determine whether a number is even or odd.
const number = 12;
console.log(number % 2 === 0);12 ÷ 2 = 6 remainder 0
12 % 2 = 0
Even Number
13 ÷ 2 = 6 remainder 1
13 % 2 = 1
Odd 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);2 ** 3
2 × 2 × 2
│
▼
8Increment Operator (++)
The increment operator increases a numeric variable by one.
let score = 10;
score++;
console.log(score);The increment operation is equivalent to adding one to the current value.
let score = 10;
score = score + 1;
console.log(score);Decrement Operator (--)
The decrement operator decreases a numeric variable by one.
let lives = 3;
lives--;
console.log(lives);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);Postfix returns the original value first and then updates the variable.
let number = 5;
const result = ++number;
console.log(result);
console.log(number);Prefix updates the variable first and then returns the updated value.
Postfix: value++
1. Return current value
2. Increase value
Prefix: ++value
1. Increase value
2. 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);let score = 100;
score = 200;
console.log(score);- = 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);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);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);Equal Operator (==)
The loose equality operator compares values after allowing type coercion.
console.log(5 == 5);
console.log(5 == '5');
console.log(0 == false);- 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);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');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);const age = 22;
const minimumAge = 18;
const canRegister = age >= minimumAge;
console.log(canRegister);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);Condition A Condition B A && B
-------------------------------------
true true true
true false false
false true false
false 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);Condition A Condition B A || B
-------------------------------------
true true true
true false true
false true true
false false falseLogical NOT Operator (!)
The logical NOT operator reverses the boolean meaning of a value.
const isLoggedIn = true;
console.log(!isLoggedIn);console.log(!!'JavaScript');
console.log(!!'');
console.log(!!100);
console.log(!!0);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!');Because the first value is false, JavaScript does not evaluate the second operand.
const userName = '';
const displayName = userName || 'Guest';
console.log(displayName);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);console.log(0 ?? 100);
console.log('' ?? 'Default');
console.log(false ?? true);- 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);value || default
Uses default for:
false, 0, '', null, undefined, NaN
value ?? default
Uses 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);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);console.log(-10);
console.log(-'25');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 () {});console.log(typeof null);- 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);- 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); 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);- 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);let message = 'Hello';
message += ' JavaScript';
console.log(message);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);const user = {
name: 'Rahul',
address: {
city: 'Mumbai'
}
};
console.log(user.address?.city);const user = {
name: 'Rahul'
};
const city = user.address?.city ?? 'Unknown';
console.log(city);- 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);5 = 0101
3 = 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);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, typeof
Multiplication *, /, %
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);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);Using Parentheses
Parentheses can change evaluation order and make complex expressions easier to understand.
console.log(10 + 5 * 2);console.log((10 + 5) * 2);- 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 operators
const subtotal = productPrice * quantity;
const discountAmount =
subtotal * (discountPercent / 100);
let finalAmount =
subtotal - discountAmount;
// Logical operators
const canPlaceOrder =
isLoggedIn && hasValidAddress;
// Optional chaining and nullish coalescing
const membershipType =
user.membership?.type ?? 'standard';
// Strict comparison
const isPremium =
membershipType === 'premium';
// Ternary operator
const delivery =
isPremium ? 0 : deliveryCharge;
// Assignment operator
finalAmount += delivery;
// Comparison operator
const 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);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 comparison
let value = 10;
// if (value = 20) {}
// ❌ Loose equality
console.log(5 == '5');
// ❌ String concatenation
console.log('10' + 20);
// ❌ || replaces valid zero
console.log(0 || 100);
// ❌ Confusing precedence
console.log(10 + 5 * 2);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);Frequently Asked Questions
What is an operator in JavaScript?
An operator is a symbol or keyword that performs an operation on one or more values.
What is an operand?
An operand is a value on which an operator performs an operation.
What are arithmetic operators?
Arithmetic operators perform mathematical calculations such as addition, subtraction, multiplication, and division.
What does the % operator do?
The % operator returns the remainder after division.
Does % calculate a percentage?
No. The % operator calculates a remainder, not a percentage.
What does ** mean?
The ** operator performs exponentiation and raises one value to the power of another.
What does ++ do?
The ++ operator increases a numeric variable by one.
What does -- do?
The -- operator decreases a numeric variable by one.
What is the difference between value++ and ++value?
value++ returns the old value before incrementing, while ++value increments first and returns the new value.
What is an assignment operator?
An assignment operator stores or updates a value in a variable.
What does += mean?
It adds a value to the current variable value and stores the result back in the variable.
What is the difference between = and ===?
= assigns a value, while === compares both value and data type.
What is the difference between == and ===?
== allows type coercion, while === compares value and type without loose equality coercion.
Which equality operator should I normally use?
Use === for most equality comparisons.
What does && mean?
The && operator is logical AND. In boolean conditions, both conditions must succeed.
What does || mean?
The || operator is logical OR. In boolean conditions, at least one condition must succeed.
What does ! mean?
The ! operator reverses the boolean meaning of a value.
What does !! do?
Double NOT converts a value into its boolean equivalent.
What is short-circuit evaluation?
Short-circuit evaluation means JavaScript stops evaluating a logical expression when the final result can already be determined.
What does ?? mean?
The ?? operator returns a fallback value only when the left operand is null or undefined.
What is the difference between || and ???
|| uses a fallback for any falsy value, while ?? uses a fallback only for null or undefined.
Why should I use ?? for numeric configuration?
It preserves valid values such as 0 instead of replacing them with a default.
What is a unary operator?
A unary operator works with one operand.
What does unary + do?
Unary + attempts to convert a value into a number.
What does typeof do?
typeof returns a string describing the type of a value.
Why does typeof null return object?
It is a historical behavior in JavaScript.
What does delete do?
The delete operator removes a property from an object.
What is the ternary operator?
The ternary operator chooses between two values based on a condition.
What is the ternary syntax?
The syntax is condition ? valueIfTrue : valueIfFalse.
Should I use nested ternary operators?
Small nested ternaries can work, but complex decision logic is usually clearer with if...else.
What does ?. mean?
The optional chaining operator safely accesses properties when parent values may be null or undefined.
What happens when optional chaining cannot find a property?
The expression returns undefined instead of throwing an error caused by accessing a property of null or undefined.
Can I combine ?. and ???
Yes. Optional chaining can safely access data and ?? can provide a fallback value.
What are bitwise operators?
Bitwise operators perform operations on binary integer representations.
What is operator precedence?
Operator precedence determines which operation is evaluated first.
What is associativity?
Associativity determines the evaluation direction when operators have the same precedence.
Why should I use parentheses?
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.