LearnContact
Lesson 945 min read

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 You Will Learn
  • 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.

Basic Operator Example
const firstNumber = 10;
const secondNumber = 20;

const result = firstNumber + secondNumber;

console.log(result);
Output
Operator Structure
10 + 20
│  │  │
│  │  └── Operand
│  │
│  └───── Operator
│
└──────── Operand

In this expression, 10 and 20 are the values being operated on, while + is the operator that performs addition.

Simple Definition
  • 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.

Operator Analogy
First Value       Operator       Second Value
    10               +               20
     │               │                │
     └───────────────┼────────────────┘
                     ▼
              ┌─────────────┐
              │  Addition   │
              │   Machine   │
              └─────────────┘
                     │
                     ▼
                    30

Different 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.

Operands
const result = 50 - 20;

console.log(result);
Output
Expression Breakdown
50 - 20
│  │  │
│  │  └── Right Operand
│  │
│  └───── Operator
│
└──────── Left Operand

Operators 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.

Operator Categories
JavaScript Operators
        │
        ├── Arithmetic Operators
        ├── Assignment Operators
        ├── Comparison Operators
        ├── Logical Operators
        ├── Unary Operators
        ├── Ternary Operator
        ├── String Operators
        ├── Nullish Coalescing
        ├── Optional Chaining
        ├── Bitwise Operators
        └── Type Operators

Arithmetic

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.

Arithmetic Operators
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--
Arithmetic Examples
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);
Output

Addition Operator (+)

The addition operator adds numeric values.

Addition
const firstNumber = 25;
const secondNumber = 15;

const total = firstNumber + secondNumber;

console.log(total);
Output
Adding Multiple Values
const productPrice = 500;
const deliveryCharge = 50;
const tax = 90;

const finalPrice = productPrice + deliveryCharge + tax;

console.log(finalPrice);
Output
The + Operator Has Two Behaviors
  • 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.

Subtraction
const balance = 1000;
const purchase = 350;

const remainingBalance = balance - purchase;

console.log(remainingBalance);
Output

Multiplication Operator (*)

The multiplication operator multiplies two numeric values.

Multiplication
const price = 499;
const quantity = 3;

const total = price * quantity;

console.log(total);
Output

Division Operator (/)

The division operator divides the left operand by the right operand.

Division
const totalAmount = 1000;
const people = 4;

const amountPerPerson = totalAmount / people;

console.log(amountPerPerson);
Output
Division by Zero
console.log(10 / 0);
console.log(-10 / 0);
console.log(0 / 0);
Output

Remainder Operator (%)

The remainder operator returns the remainder left after division.

Remainder
console.log(10 % 3);
console.log(20 % 5);
console.log(17 % 4);
Output

The remainder operator is commonly used to determine whether a number is even or odd.

Even or Odd
const number = 12;

console.log(number % 2 === 0);
Output
Remainder Process
12 ÷ 2 = 6 remainder 0
12 % 2 = 0
Even Number


13 ÷ 2 = 6 remainder 1
13 % 2 = 1
Odd Number

Exponentiation Operator (**)

The exponentiation operator raises the left operand to the power of the right operand.

Exponentiation
console.log(2 ** 3);
console.log(5 ** 2);
console.log(10 ** 3);
Output
Exponentiation Process
2 ** 3

2 × 2 × 2
    │
    ▼
    8

Increment Operator (++)

The increment operator increases a numeric variable by one.

Increment
let score = 10;

score++;

console.log(score);
Output

The increment operation is equivalent to adding one to the current value.

Equivalent Increment
let score = 10;

score = score + 1;

console.log(score);
Output

Decrement Operator (--)

The decrement operator decreases a numeric variable by one.

Decrement
let lives = 3;

lives--;

console.log(lives);
Output

Prefix vs Postfix

Increment and decrement operators can appear before or after a variable. Their position affects the value returned by the expression.

Postfix Increment
let number = 5;

const result = number++;

console.log(result);
console.log(number);
Output

Postfix returns the original value first and then updates the variable.

Prefix Increment
let number = 5;

const result = ++number;

console.log(result);
console.log(number);
Output

Prefix updates the variable first and then returns the updated value.

Prefix vs Postfix
Postfix: value++

1. Return current value
2. Increase value


Prefix: ++value

1. Increase value
2. Return new value
Keep Increment Logic Simple
  • 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.

Assignment Operators
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 ** 2

Basic Assignment Operator (=)

The assignment operator stores the value on its right side inside the variable on its left side.

Basic Assignment
let score = 100;

console.log(score);
Output
Reassignment
let score = 100;

score = 200;

console.log(score);
Output
Assignment is Not Comparison
  • = 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.

Addition Assignment
let score = 100;

score += 50;

console.log(score);
Output
Equivalent Code
score += 50

is equivalent to

score = score + 50

Other Assignment Operators

Compound Assignment
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);
Output

Comparison Operators

Comparison operators compare values and return a boolean result: true or false.

Comparison Operators
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 to
Comparison Examples
console.log(10 > 5);
console.log(10 < 5);
console.log(10 >= 10);
console.log(5 <= 10);
Output

Equal Operator (==)

The loose equality operator compares values after allowing type coercion.

Loose Equality
console.log(5 == 5);
console.log(5 == '5');
console.log(0 == false);
Output
Loose Equality Performs Conversion
  • 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.

Strict Equality
console.log(5 === 5);
console.log(5 === '5');
console.log(0 === false);
Output
Loose vs Strict Equality
5 == '5'
│
├── Values compared after coercion
└── true


5 === '5'
│
├── Value: similar
├── Type: different
└── false
Recommended Practice
  • 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.

Not Equal
console.log(10 != 5);
console.log(5 != '5');

console.log(10 !== 5);
console.log(5 !== '5');
Output

The !== operator is generally preferred because it compares values without loose equality coercion.

Greater Than and Less Than Operators

Relational Operators
const age = 20;

console.log(age > 18);
console.log(age < 18);
console.log(age >= 20);
console.log(age <= 20);
Output
Real-World Age Check
const age = 22;
const minimumAge = 18;

const canRegister = age >= minimumAge;

console.log(canRegister);
Output

Logical Operators

Logical operators combine, select, or reverse conditions.

Logical Operators
Operator    Name
---------------------------
&&          Logical AND
||          Logical OR
!           Logical NOT

Logical AND Operator (&&)

The logical AND operator requires both conditions to be truthy for the complete condition to succeed.

Logical AND
const age = 25;
const hasLicense = true;

const canDrive = age >= 18 && hasLicense;

console.log(canDrive);
Output
AND Truth Table
Condition A    Condition B    A && B
-------------------------------------
true           true           true
true           false          false
false          true           false
false          false          false

Logical OR Operator (||)

The logical OR operator succeeds when at least one condition is truthy.

Logical OR
const isAdmin = false;
const isEditor = true;

const canEdit = isAdmin || isEditor;

console.log(canEdit);
Output
OR Truth Table
Condition A    Condition B    A || B
-------------------------------------
true           true           true
true           false          true
false          true           true
false          false          false

Logical NOT Operator (!)

The logical NOT operator reverses the boolean meaning of a value.

Logical NOT
const isLoggedIn = true;

console.log(!isLoggedIn);
Output
Double NOT
console.log(!!'JavaScript');
console.log(!!'');
console.log(!!100);
console.log(!!0);
Output

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.

AND Short-Circuit
const isLoggedIn = false;

isLoggedIn && console.log('Welcome back!');
Output

Because the first value is false, JavaScript does not evaluate the second operand.

OR Short-Circuit
const userName = '';

const displayName = userName || 'Guest';

console.log(displayName);
Output
Short-Circuit Flow
AND (&&)

false && secondValue
  │
  └── Stop immediately


OR (||)

true || secondValue
 │
 └── Stop immediately

Nullish Coalescing Operator (??)

The nullish coalescing operator returns the right operand only when the left operand is null or undefined.

Nullish Coalescing
const userName = null;

const displayName = userName ?? 'Guest';

console.log(displayName);
Output
Preserving Valid Falsy Values
console.log(0 ?? 100);
console.log('' ?? 'Default');
console.log(false ?? true);
Output
When Does ?? Use the Default?
  • 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.

OR vs Nullish
const quantity = 0;

console.log(quantity || 10);
console.log(quantity ?? 10);
Output
Comparison
value || default
Uses default for:
false, 0, '', null, undefined, NaN


value ?? default
Uses default for:
null, undefined
Choosing Between || and ??
  • 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.

Unary Operator Examples
const value = '100';

console.log(typeof value);
console.log(+value);
console.log(-value);
console.log(!value);
Output

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.

Unary Plus
const value = '100';

const result = +value;

console.log(result);
console.log(typeof result);
Output
Unary Minus
console.log(-10);
console.log(-'25');
Output

typeof Operator

The typeof operator returns a string describing the type of a value.

typeof Examples
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 () {});
Output
typeof null
console.log(typeof null);
Output
Remember 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.

Delete Object Property
const user = {
    name: 'Rahul',
    age: 25,
    city: 'Mumbai'
};

delete user.city;

console.log(user);
Output
About delete
  • 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.

Ternary Syntax
condition ? valueIfTrue : valueIfFalse
Ternary Example
const age = 20;

const status = age >= 18 ? 'Adult' : 'Minor';

console.log(status);
Output
Ternary Flow
         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.

Nested Ternary
const score = 85;

const grade =
    score >= 90 ? 'A' :
    score >= 75 ? 'B' :
    score >= 60 ? 'C' :
    'Fail';

console.log(grade);
Output
Avoid Complex Nested Ternaries
  • 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.

String Concatenation
const firstName = 'Rahul';
const lastName = 'Sharma';

const fullName = firstName + ' ' + lastName;

console.log(fullName);
Output
String Assignment
let message = 'Hello';

message += ' JavaScript';

console.log(message);
Output

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.

Without Optional Chaining
const user = {
    name: 'Rahul'
};

// This would cause an error:
// console.log(user.address.city);
With Optional Chaining
const user = {
    name: 'Rahul'
};

console.log(user.address?.city);
Output
Existing Nested Property
const user = {
    name: 'Rahul',
    address: {
        city: 'Mumbai'
    }
};

console.log(user.address?.city);
Output
Optional Chaining with Default
const user = {
    name: 'Rahul'
};

const city = user.address?.city ?? 'Unknown';

console.log(city);
Output
Optional Chaining Benefits
  • 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.

Bitwise Operators
Operator    Name
-----------------------------
&           Bitwise AND
|           Bitwise OR
^           Bitwise XOR
~           Bitwise NOT
<<          Left Shift
>>          Signed Right Shift
>>>         Unsigned Right Shift
Bitwise Examples
console.log(5 & 3);
console.log(5 | 3);
console.log(5 ^ 3);
console.log(5 << 1);
console.log(5 >> 1);
Output
Binary Example
5 = 0101
3 = 0011

Bitwise AND (&)

  0101
& 0011
------
  0001

Result = 1
For Beginners
  • 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.

Precedence Example
const result = 10 + 5 * 2;

console.log(result);
Output

Multiplication has higher precedence than addition, so 5 * 2 is evaluated first.

Evaluation Order
10 + 5 * 2
     │
     ▼
10 + 10
   │
   ▼
  20
Simplified Precedence Order
Higher Priority
      │
      ▼
Parentheses          ()
Exponentiation       **
Unary Operators      !, +value, -value, typeof
Multiplication       *, /, %
Addition             +, -
Comparison           <, >, <=, >=
Equality             ==, ===, !=, !==
Logical AND          &&
Logical OR           ||
Nullish Coalescing   ??
Ternary              ? :
Assignment           =
      │
      ▼
Lower Priority

Operator Associativity

Associativity determines the evaluation direction when operators have the same precedence.

Left-to-Right Associativity
const result = 100 / 10 * 2;

console.log(result);
Output
Left-to-Right Evaluation
100 / 10 * 2

100 / 10
    │
    ▼
   10 * 2
      │
      ▼
     20

Assignment operators are commonly evaluated from right to left.

Right-to-Left Assignment
let a;
let b;

a = b = 50;

console.log(a);
console.log(b);
Output

Using Parentheses

Parentheses can change evaluation order and make complex expressions easier to understand.

Without Parentheses
console.log(10 + 5 * 2);
Output
With Parentheses
console.log((10 + 5) * 2);
Output
Use Parentheses for Clarity
  • 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.

shopping-calculator.js
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);
Output
Application Operator Flow
Product Price × Quantity
          │
          ▼
       Subtotal
          │
          ├── Calculate Discount
          │
          ▼
   Amount After Discount
          │
          ├── Check Membership
          │
          ├── Determine Delivery
          │
          ▼
      Final Amount
          │
          ├── Check Login
          ├── Check Address
          │
          ▼
    Can Place Order

Real-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

Avoid These 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.
Common Operator Mistakes
// ❌ 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);
Output

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.
Recommended Operator Style
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);
Output

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.

Lesson 9 Completed
  • 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.
Next Lesson →

JavaScript Input & Output