Skip to main content
JavaScript Basics
CHAPTER 04 Beginner

JavaScript Operators

Updated: May 12, 2026
20 min read

# JavaScript Operators

Welcome to Chapter 4! Now that we know how to store data inside variables, we need to know how to perform actions on that data. We want to add numbers, compare scores, and combine strings. This is where Operators come in.

In this chapter, we will learn about the different types of operators JavaScript provides and build a functioning simple calculator.

1. Introduction

An operator is a special symbol that performs an operation on one or more variables or values (called "operands"). For example, in 5 + 2, the + is the operator, and 5 and 2 are the operands.

JavaScript provides several categories of operators:

  • Arithmetic Operators (for math)
  • Assignment Operators (for assigning values)
  • Comparison Operators (for comparing values)
  • Logical Operators (for combining logic)
  • Ternary Operator (a shortcut for if/else conditions)

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Perform mathematical calculations using arithmetic operators.
  • Use assignment operators to update variable values quickly.
  • Compare values to check if they are equal, greater, or smaller.
  • Combine multiple conditions using logical AND/OR.
  • Build a working Simple Calculator project.

---

3. Arithmetic Operators

These operators are used to perform basic math on numbers.

OperatorDescriptionExample (if x = 10)Result
+Additionx + 515
-Subtractionx - 55
*Multiplicationx * 550
/Divisionx / 25
%Modulus (Remainder)x % 31
Exponentiationx 2100

4. Assignment Operators

These operators assign values to JavaScript variables.

OperatorExampleSame As
=x = 10x = 10
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5

5. Comparison Operators

These are used to compare two values. They always return a Boolean (true or false).

OperatorDescriptionExample (if x = 5)Result
==Equal tox == 5true
===Strict Equal (Value AND Type)x === "5"false
!=Not equalx != 8true
>Greater thanx > 8false
<Less thanx < 8true
>=Greater than or equal tox >= 5true

6. Logical Operators

Logical operators are used to determine the logic between variables or values.

OperatorDescriptionExample (x=6, y=3)Result
&&AND (both must be true)(x < 10 && y > 1)true
||OR (one must be true)(x == 5 || y == 5)false
!NOT (reverses the boolean)!(x == y)true

---

7. Real-world Examples & Code Snippets

Example 1: Basic Math operations

javascript
12345678
// Example JavaScript
let a = 20;
let b = 4;

console.log("Addition: ", a + b);       // 24
console.log("Subtraction: ", a - b);    // 16
console.log("Multiplication: ", a * b); // 80
console.log("Division: ", a / b);       // 5

Example 2: Understanding Modulus (%)

The Modulus operator returns the *remainder* of a division. It is incredibly useful for determining if a number is even or odd.

javascript
123
// Example JavaScript
console.log(10 % 3); // Output: 1 (Because 10 / 3 is 9, remainder 1)
console.log(10 % 2); // Output: 0 (Even numbers always have 0 remainder with 2)

Example 3: Increment and Decrement

A quick way to add or subtract 1. Often used in loops and counters.

javascript
12345678
// Example JavaScript
let score = 0;
score++; // Adds 1. Same as score = score + 1;
score++; // Adds 1.
console.log(score); // Output: 2

score--; // Subtracts 1.
console.log(score); // Output: 1

Example 4: The += Assignment Operator

Imagine a shopping cart where you keep adding the price of new items to the total.

javascript
12345678
// Example JavaScript
let cartTotal = 50;
let shoesPrice = 80;

// Add shoesPrice to cartTotal
cartTotal += shoesPrice; 

console.log("Your new total is: $" + cartTotal); // Output: $130

Example 5: Equal (==) vs Strict Equal (===)

This is a classic JavaScript trap. == only checks if the values look the same. === checks if the values AND data types are exactly the same.

javascript
123456
// Example JavaScript
let num = 10;       // Number
let textStr = "10"; // String

console.log(num == textStr);  // true (JS converts text to number behind the scenes)
console.log(num === textStr); // false (Different types: Number vs String)

Best Practice: Always use === to prevent unexpected bugs!

Example 6: Logical AND (&&)

Imagine a login system. You must have the right username AND the right password.

javascript
123456
// Example JavaScript
let hasRightUsername = true;
let hasRightPassword = true;

let canLogin = hasRightUsername && hasRightPassword;
console.log("Login Success: ", canLogin); // Output: true

Example 7: Logical OR (||)

Imagine an online store with free shipping if the order is over $50 OR if the user is a VIP member.

javascript
123456
// Example JavaScript
let orderTotal = 30;
let isVipMember = true;

let getsFreeShipping = (orderTotal >= 50) || isVipMember;
console.log("Free Shipping: ", getsFreeShipping); // Output: true

Example 8: Logical NOT (!)

It simply flips true to false, and false to true.

javascript
123
// Example JavaScript
let isRaining = true;
console.log(!isRaining); // Output: false

Example 9: String Concatenation Operator

The + operator acts differently with strings. It joins them together.

javascript
123456
// Example JavaScript
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;

console.log(fullName); // Output: John Doe

Example 10: The Ternary Operator (? :)

This is a one-line shorthand for an if-else statement (which we will learn deeply in Chapter 6). Format: condition ? valueiftrue : valueiffalse

javascript
12345
// Example JavaScript
let age = 18;
let canVote = (age >= 18) ? "Yes, you can vote" : "No, too young";

console.log(canVote); // Output: Yes, you can vote

---

8. Common Mistakes for Beginners

  1. 1. Using = instead of == for comparison:
javascript
123456789101112131415161718
   let x = 10;
   // Wrong: This ASSIGNS 5 to x, and always returns true!
   console.log(x = 5); 
   // Correct: This COMPARES x to 5.
   console.log(x === 5);
   ```
2. **Forgetting `===` strict equality:** Getting into the habit of using `==` will cause weird bugs when handling form inputs (which are often Strings, even if the user typed a number).

## 9. Best Practices

- Always use `===` and `!==` instead of `==` and `!=`.
- When writing complex logical statements, use parentheses `()` to group logic, making it easier to read. Example: `if ((x > 5) && (y < 10))`

## 10. Mini Project: Simple Web Calculator

Let&#039;s build a basic calculator using HTML, CSS, and JS operators.

**HTML:**

html <!-- Example HTML --> <!DOCTYPE html> <html> <head> <style> /* Example CSS */ .calc-box { width: 250px; padding: 20px; border: 1px solid #000; border-radius: 10px; font-family: Arial; } input { width: 90%; margin-bottom: 10px; padding: 5px; } button { padding: 10px; width: 45%; cursor: pointer; } #calc-result { font-size: 24px; font-weight: bold; margin-top: 15px; } </style> </head> <body>

<div class="calc-box"> <h3>Simple Calculator</h3> <input type="number" id="num1" placeholder="Enter first number"> <input type="number" id="num2" placeholder="Enter second number"> <br> <button onclick="addNumbers()">Add (+)</button> <button onclick="multiplyNumbers()">Multiply (*)</button> <div id="calc-result">Result: 0</div> </div>

<script src="calculator.js"></script> </body> </html>

1
**calculator.js:**

javascript // Example JavaScript function addNumbers() { // 1. Get the values from the inputs and convert them to numbers let n1 = Number(document.getElementById("num1").value); let n2 = Number(document.getElementById("num2").value); // 2. Perform the arithmetic operation let sum = n1 + n2; // 3. Output to the screen document.getElementById("calc-result").innerHTML = "Result: " + sum; }

function multiplyNumbers() { let n1 = Number(document.getElementById("num1").value); let n2 = Number(document.getElementById("num2").value); let product = n1 * n2; document.getElementById("calc-result").innerHTML = "Result: " + product; } `` How it works: We read the values the user typed, force them to become strict Numbers (because HTML inputs always return text strings by default), apply our Arithmetic Operators (+ and *), and display the result.

11. Exercises

  1. 1. Create variables x = 10 and y = 3. Console log the remainder of x divided by y.
  1. 2. Write a single line of code that adds 5 to a variable score using an assignment operator.
  1. 3. Write a console log statement using the ternary operator that checks if a variable temperature is greater than 30. If true, print "Hot", otherwise print "Cold".

12. MCQs (Multiple Choice Questions)

Q1: What is the output of 5 == "5"? A) false B) true C) error D) undefined *Answer: B (Because == ignores data types)*

Q2: What does the % operator do? A) Calculates percentages B) Divides two numbers C) Returns the division remainder D) Multiplies two numbers *Answer: C*

Q3: Which logical operator means "OR"? A) && B) !! C) || D) == *Answer: C*

13. Interview Questions

Q: What is the difference between == and === in JavaScript? *A: == is the abstract equality operator; it performs type coercion, meaning it converts types to match before comparing (e.g., 1 == "1" is true). === is the strict equality operator; it checks both the value and the data type without coercion (e.g., 1 === "1" is false).*

Q: Explain how the ternary operator works. *A: The ternary operator is a shorthand conditional statement. It takes three operands: a condition followed by a question mark (?), an expression to execute if the condition is true followed by a colon (:), and an expression to execute if false.*

14. Summary

  • Arithmetic operators (+, -, *, /, %) perform math.
  • Assignment operators (=, +=, -=) shortcut updating variables.
  • Comparison operators (>, <, ===) compare variables and return Booleans.
  • Logical operators (&&, ||, !) combine multiple boolean conditions together.

15. Next Chapter Recommendation

We have used
alert(), console.log()`, and basic DOM text injection. Next, we will fully formalize how to interact with the user via pop-ups and browser outputs in JavaScript User Input and Output.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·