July 31, 202610 min readAdmin User

JavaScript Operators: A Beginner-Friendly Guide with Simple Examples

Learn JavaScript operators with beginner-friendly examples. Understand arithmetic, assignment, comparison, logical, increment, string, type, and ternary operators with practical programs.

Web DevelopmentJavaScriptJavaScriptJavaScript OperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsJavaScript for BeginnersJavaScript TutorialProgramming BasicsFrontend DevelopmentWeb Development
JavaScript Operators: A Beginner-Friendly Guide with Simple Examples

JavaScript operators are special symbols used to perform actions on values and variables.

They can be used to:

  • Add or subtract numbers
  • Compare two values
  • Assign values to variables
  • Check multiple conditions
  • Increase or decrease a number
  • Work with strings and data types

Example:


const firstNumber = 10;
const secondNumber = 5;

const total = firstNumber + secondNumber;

console.log(total);

Output:


15

In this example, the + symbol is an operator. It adds the two values together.

Understanding operators is essential because they are used in calculations, conditions, loops, forms, and almost every JavaScript application.

What Is an Operator?

An operator is a symbol that performs an operation on one or more values.

Example:


const result = 10 + 20;

Here:

  • 10 and 20 are operands.
  • + is the operator.
  • 30 is the result.

JavaScript provides different types of operators for different tasks.

Main Types of JavaScript Operators

The most commonly used JavaScript operators are:

  1. Arithmetic operators
  2. Assignment operators
  3. Comparison operators
  4. Logical operators
  5. Increment and decrement operators
  6. String operators
  7. Type operators
  8. Ternary operator

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations.

OperatorMeaning+Addition-Subtraction*Multiplication/Division%Remainder**Exponentiation

Addition Operator

The + operator adds two numbers.


const firstNumber = 20;
const secondNumber = 10;

const result = firstNumber + secondNumber;

console.log(result);

Output:


30

Subtraction Operator

The - operator subtracts one number from another.


const totalAmount = 1000;
const discount = 200;

const finalAmount = totalAmount - discount;

console.log(finalAmount);

Output:


800

Multiplication Operator

The * operator multiplies two numbers.


const productPrice = 500;
const quantity = 3;

const totalPrice = productPrice * quantity;

console.log(totalPrice);

Output:


1500

Division Operator

The / operator divides one value by another.


const totalMarks = 500;
const subjects = 5;

const averageMarks = totalMarks / subjects;

console.log(averageMarks);

Output:


100

Remainder Operator

The % operator returns the remainder after division.


console.log(10 % 3);

Output:


1

This operator is useful for checking whether a number is even or odd.


const number = 8;

console.log(number % 2);

Output:


0

When a number divided by 2 gives a remainder of 0, it is even.

Exponentiation Operator

The ** operator raises one number to the power of another.


const result = 2 ** 3;

console.log(result);

Output:


8

This means:


2 × 2 × 2 = 8

2. Assignment Operators

Assignment operators are used to assign or update values in variables.

OperatorExampleMeaning=x = 10Assign value+=x += 5Add and assign-=x -= 5Subtract and assign*=x *= 2Multiply and assign/=x /= 2Divide and assign%=x %= 3Remainder and assign

Basic Assignment Operator

The = operator assigns a value to a variable.


let score = 10;

console.log(score);

Output:


10

Add and Assign


let score = 10;

score += 5;

console.log(score);

Output:


15

This is the shorter version of:


score = score + 5;

Subtract and Assign


let balance = 1000;

balance -= 200;

console.log(balance);

Output:


800

Multiply and Assign


let price = 100;

price *= 3;

console.log(price);

Output:


300

Divide and Assign


let total = 100;

total /= 4;

console.log(total);

Output:


25

3. Comparison Operators

Comparison operators compare two values and return a Boolean result.

The result is always:


true

or:


false

OperatorMeaning==Equal value===Equal value and data type!=Not equal value!==Not equal value or type>Greater than<Less than>=Greater than or equal<=Less than or equal

Equal Operator

The == operator checks whether the values are equal.


console.log(10 == "10");

Output:


true

It returns true because == compares the values but does not strictly compare their data types.

Strict Equal Operator

The === operator compares both value and data type.


console.log(10 === "10");

Output:


false

Here:

  • 10 is a number.
  • "10" is a string.

Their values may look similar, but their data types are different.

Use === instead of == in modern JavaScript.

Not Equal Operator


console.log(10 != 5);

Output:


true

Strict Not Equal Operator


console.log(10 !== "10");

Output:


true

The value appears similar, but the data types are different.

Greater Than Operator


const age = 25;

console.log(age > 18);

Output:


true

Less Than Operator


const productPrice = 500;

console.log(productPrice < 1000);

Output:


true

Greater Than or Equal Operator


const marks = 40;

console.log(marks >= 40);

Output:


true

Less Than or Equal Operator


const age = 18;

console.log(age <= 18);

Output:


true

4. Logical Operators

Logical operators are used to combine or reverse conditions.

The three main logical operators are:

OperatorName&&Logical AND`!Logical NOT

Logical AND Operator

The && operator returns true only when both conditions are true.


const age = 25;
const hasDrivingLicense = true;

const canDrive = age >= 18 && hasDrivingLicense;

console.log(canDrive);

Output:


true

Both conditions are true, so the final result is true.

Another example:


const userName = "Rahul";
const password = "12345";

const canLogin =
  userName === "Rahul" &&
  password === "12345";

console.log(canLogin);

Output:


true

Logical OR Operator

The || operator returns true when at least one condition is true.


const isAdmin = false;
const isEditor = true;

const hasAccess = isAdmin || isEditor;

console.log(hasAccess);

Output:


true

The user is not an admin, but they are an editor. Therefore, access is allowed.

Logical NOT Operator

The ! operator reverses a Boolean value.


const isLoggedIn = true;

console.log(!isLoggedIn);

Output:


false

Another example:


const isBlocked = false;

if (!isBlocked) {
  console.log("User can access the account");
}

Output:


User can access the account

5. Increment and Decrement Operators

Increment and decrement operators increase or decrease a value by one.

OperatorMeaning++Increase by one--Decrease by one

Increment Operator


let count = 5;

count++;

console.log(count);

Output:


6

This is the shorter version of:


count = count + 1;

Decrement Operator


let count = 5;

count--;

console.log(count);

Output:


4

Prefix and Postfix Increment

JavaScript supports two forms:


++count;
count++;

When used alone, both increase the value by one.


let firstCount = 5;
let secondCount = 5;

++firstCount;
secondCount++;

console.log(firstCount);
console.log(secondCount);

Output:


6
6

However, they behave differently when used during assignment.

Postfix


let count = 5;
let result = count++;

console.log(result);
console.log(count);

Output:


5
6

The old value is assigned first, and then the count increases.

Prefix


let count = 5;
let result = ++count;

console.log(result);
console.log(count);

Output:


6
6

The value increases first, and then it is assigned.

For beginners, use increment and decrement on separate lines whenever possible. Clever code is often just confusing code wearing sunglasses.

6. String Operators

The + operator can also join strings.


const firstName = "Rahul";
const lastName = "Sharma";

const fullName = firstName + " " + lastName;

console.log(fullName);

Output:


Rahul Sharma

This process is called string concatenation.

Adding a String and Number


const value = "10" + 5;

console.log(value);

Output:


105

Because one value is a string, JavaScript converts the number into text and joins both values.

To perform mathematical addition, convert the string to a number.


const value = Number("10") + 5;

console.log(value);

Output:


15

Using Template Literals

Template literals provide a cleaner way to combine strings and variables.


const userName = "Rahul";
const age = 24;

const message =
  `My name is ${userName} and I am ${age} years old.`;

console.log(message);

Output:


My name is Rahul and I am 24 years old.

7. Type Operators

Type operators help check the type or structure of a value.

The most common type operators are:

  • typeof
  • instanceof

typeof Operator

The typeof operator returns the data type of a value.


console.log(typeof "Hello");
console.log(typeof 25);
console.log(typeof true);

Output:


string
number
boolean

Example with variables:


const userName = "Rahul";
const age = 24;
const isDeveloper = true;

console.log(typeof userName);
console.log(typeof age);
console.log(typeof isDeveloper);

instanceof Operator

The instanceof operator checks whether an object belongs to a particular class or constructor.


const currentDate = new Date();

console.log(currentDate instanceof Date);

Output:


true

This is more useful in intermediate and advanced JavaScript.

8. Ternary Operator

The ternary operator is a shorter way to write a simple if...else condition.

Syntax:


condition ? valueIfTrue : valueIfFalse;

Example:


const age = 20;

const message =
  age >= 18 ? "You are an adult" : "You are a minor";

console.log(message);

Output:


You are an adult

The same logic using if...else would look like this:


const age = 20;
let message;

if (age >= 18) {
  message = "You are an adult";
} else {
  message = "You are a minor";
}

Use the ternary operator for short and simple conditions.

Avoid using it for large or complicated logic because it can make code difficult to read.

Operator Precedence

Operator precedence determines which operation runs first.

Example:


const result = 10 + 5 * 2;

console.log(result);

Output:


20

Multiplication runs before addition.

The calculation happens like this:


5 × 2 = 10
10 + 10 = 20

Use parentheses when you want addition to happen first.


const result = (10 + 5) * 2;

console.log(result);

Output:


30

Parentheses also make calculations easier to understand.

Practical Example: Product Price Calculation


const productPrice = 1000;
const quantity = 2;
const discount = 200;

const totalAmount = productPrice * quantity;
const finalAmount = totalAmount - discount;

console.log("Total Amount:", totalAmount);
console.log("Final Amount:", finalAmount);

Output:


Total Amount: 2000
Final Amount: 1800

Practical Example: Login Validation


const enteredEmail = "user@example.com";
const enteredPassword = "12345";

const savedEmail = "user@example.com";
const savedPassword = "12345";

const isValidUser =
  enteredEmail === savedEmail &&
  enteredPassword === savedPassword;

console.log(isValidUser);

Output:


true

This example uses:

  • Strict comparison
  • Logical AND
  • Boolean result

Practical Example: Even or Odd Number


const number = 8;

const result =
  number % 2 === 0 ? "Even Number" : "Odd Number";

console.log(result);

Output:


Even Number

Common Beginner Mistakes

Using Assignment Instead of Comparison

Incorrect:


let age = 20;

if (age = 18) {
  console.log("Age is 18");
}

The single = assigns a value.

Correct:


let age = 20;

if (age === 18) {
  console.log("Age is 18");
}

Use === for strict comparison.

Using == Instead of ===

Avoid:


console.log(10 == "10");

Use:


console.log(10 === "10");

Strict comparison prevents unexpected type conversion.

Mixing Strings and Numbers


const firstValue = "100";
const secondValue = 50;

console.log(firstValue + secondValue);

Output:


10050

Correct:


const firstValue = Number("100");
const secondValue = 50;

console.log(firstValue + secondValue);

Output:


150

Writing Complex Ternary Conditions

Avoid complicated nested ternary operators.

Difficult to read:


const result =
  age < 13
    ? "Child"
    : age < 20
      ? "Teenager"
      : "Adult";

For complex logic, use if...else.

Best Practices

Follow these practices when using operators:

  • Prefer === over ==.
  • Prefer !== over !=.
  • Use parentheses in complex calculations.
  • Convert strings before mathematical operations.
  • Use meaningful variable names.
  • Keep ternary expressions simple.
  • Use logical operators carefully.
  • Avoid unnecessary prefix and postfix tricks.
  • Test conditions using console.log().

Practice Questions

Try these exercises:

  1. Add two numbers and print the result.
  2. Subtract a discount from a product price.
  3. Multiply product price by quantity.
  4. Check whether a number is even or odd.
  5. Compare two values using ===.
  6. Check whether a person is eligible to vote.
  7. Use && to check age and identity verification.
  8. Use || to allow an admin or editor access.
  9. Increase a counter using ++.
  10. Create an adult-or-minor message using the ternary operator.
  11. Convert "500" into a number before adding 100.
  12. Calculate the final amount after discount.

Conclusion

JavaScript operators are used to perform calculations, comparisons, assignments, and logical decisions.

The most important operator categories are:


Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Increment and decrement operators
String operators
Type operators
Ternary operator

Remember these key rules:


Use === instead of ==.
Use !== instead of !=.
Convert strings before calculations.
Use parentheses for clear expressions.
Keep ternary conditions simple.

Once you understand operators, the next JavaScript topic is conditional statements, including if, else if, else, and switch.