JavaScript Operators
# 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.
| Operator | Description | Example (if x = 10) | Result |
|---|---|---|---|
+ | Addition | x + 5 | 15 |
- | Subtraction | x - 5 | 5 |
* | Multiplication | x * 5 | 50 |
/ | Division | x / 2 | 5 |
% | Modulus (Remainder) | x % 3 | 1 |
| Exponentiation | x 2 | 100 |
4. Assignment Operators
These operators assign values to JavaScript variables.
| Operator | Example | Same As |
|---|---|---|
= | x = 10 | x = 10 |
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
5. Comparison Operators
These are used to compare two values. They always return a Boolean (true or false).
| Operator | Description | Example (if x = 5) | Result |
|---|---|---|---|
== | Equal to | x == 5 | true |
=== | Strict Equal (Value AND Type) | x === "5" | false |
!= | Not equal | x != 8 | true |
> | Greater than | x > 8 | false |
< | Less than | x < 8 | true |
>= | Greater than or equal to | x >= 5 | true |
6. Logical Operators
Logical operators are used to determine the logic between variables or values.
| Operator | Description | Example (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
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.
Example 3: Increment and Decrement
A quick way to add or subtract 1. Often used in loops and counters.
Example 4: The += Assignment Operator
Imagine a shopping cart where you keep adding the price of new items to the total.
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.
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.
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.
Example 8: Logical NOT (!)
It simply flips true to false, and false to true.
Example 9: String Concatenation Operator
The + operator acts differently with strings. It joins them together.
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
---
8. Common Mistakes for Beginners
-
1.
Using
=instead of==for comparison:
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>
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.
Create variables x = 10
andy = 3. Console log the remainder ofxdivided byy.
-
2.
Write a single line of code that adds 5
to a variablescoreusing an assignment operator.
-
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.