Arithmetic operators in JavaScript allow you to perform basic mathematical operations on numbers. These operators are essential for calculations in everyday programming tasks like computing totals, taxes, or discounts.
1. Addition (+
)
Adds two numbers or combines strings.
let price = 20 + 5; // 25
let greeting = "Hello, " + "World!"; // "Hello, World!"
Analogy: Adding items in your shopping cart to get the total price.
2. Subtraction (-
)
Subtracts one number from another.
let balance = 100 - 30; // 70
let difference = 50 - 20; // 30
Analogy: Calculating how much money remains after a purchase.
3. Multiplication (*
)
Multiplies two numbers.
let totalCost = 10 * 3; // 30
let area = 5 * 4; // 20
Analogy: Finding the total price when buying multiple items.
4. Division (/
)
Divides one number by another.
let pricePerItem = 30 / 3; // 10
let average = 100 / 4; // 25
Analogy: Splitting a bill evenly among friends.
5. Modulus (%
)
Returns the remainder after division.
console.log(10 % 3); // 1
console.log(15 % 5); // 0
Analogy: Checking if a number is even or odd by seeing if the remainder is 0 or not.
6. Exponentiation (**
)
Raises a number to the power of another.
let squared = 4 ** 2; // 16
let cubed = 3 ** 3; // 27
Analogy: Calculating area or volume when dimensions are squared or cubed.
These operators form the foundation for all math in JavaScript, helping you solve real-world problems involving numbers quickly and clearly.
Assignment operators in JavaScript are used to assign values to variables. The most basic assignment operator is =
, but there are also compound operators that combine arithmetic operations with assignment, making your code shorter and clearer.
1. Simple Assignment (=
)
Assigns the value on the right to the variable on the left.
let total = 10; // total is now 10
console.log(total);
2. Addition Assignment (+=
)
Adds the value on the right to the variable, then assigns the result back to the variable.
let total = 10;
total += 5; // equivalent to total = total + 5
console.log(total); // 15
Use this to increase a variable by a certain amount without rewriting the whole expression.
3. Subtraction Assignment (-=
)
Subtracts the value on the right from the variable.
let balance = 50;
balance -= 20; // equivalent to balance = balance - 20
console.log(balance); // 30
4. Multiplication Assignment (*=
)
Multiplies the variable by the value on the right.
let price = 10;
price *= 3; // equivalent to price = price * 3
console.log(price); // 30
5. Division Assignment (/=
)
Divides the variable by the value on the right.
let total = 30;
total /= 5; // equivalent to total = total / 5
console.log(total); // 6
6. Modulus Assignment (%=
)
Calculates the remainder of the variable divided by the value on the right.
let count = 10;
count %= 3; // equivalent to count = count % 3
console.log(count); // 1
Why Use Assignment Operators?
These compound operators help simplify and shorten your code, making it more readable and efficient. Instead of writing x = x + 10
, you can write x += 10
. This also reduces errors and makes updating variable values quicker and clearer. Use them whenever you want to update a variable based on its current value!
Comparison operators in JavaScript are used to compare two values. These comparisons return a Boolean value — either true
or false
— which is essential for decision-making in your programs, such as in if
statements and loops.
1. Equality (==
)
Checks if two values are equal, with type coercion. This means JavaScript converts types if needed before comparing.
console.log(5 == '5'); // true (string '5' is converted to number 5)
console.log(0 == false); // true (false is converted to 0)
Because ==
converts types, it can sometimes give unexpected results. Use it carefully.
2. Strict Equality (===
)
Checks if two values are equal without type coercion — both value and type must match.
console.log(5 === '5'); // false (number vs string)
console.log(5 === 5); // true
Use ===
for more predictable and safer comparisons.
3. Inequality (!=
)
Checks if two values are not equal, with type coercion.
console.log(5 != '10'); // true
console.log(5 != 5); // false
4. Strict Inequality (!==
)
Checks if two values are not equal without type coercion.
console.log(5 !== '5'); // true
console.log(5 !== 5); // false
5. Greater Than (>
) and Less Than (<
)
Compare if one value is larger or smaller than the other.
console.log(10 > 5); // true
console.log(3 < 2); // false
console.log('apple' > 'banana'); // false (string comparison based on Unicode)
6. Greater Than or Equal To (>=
) and Less Than or Equal To (<=
)
Check if a value is greater/less than or equal to another.
console.log(5 >= 5); // true
console.log(4 <= 3); // false
Why Comparison Operators Matter
They control program flow by enabling conditions like:
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You are too young.");
}
Summary
===
and !==
for strict comparisons (recommended).==
and !=
perform type coercion, which can lead to unexpected results.Logical operators in JavaScript allow you to combine or modify Boolean values (true
or false
). They are essential when you want to check multiple conditions at once or invert a condition in your code, especially inside if
statements.
1. AND (&&
)
The &&
operator returns true
only if both conditions are true. Otherwise, it returns false
.
let isLoggedIn = true;
let hasPermission = true;
if (isLoggedIn && hasPermission) {
console.log("Access granted");
} else {
console.log("Access denied");
}
Analogy: You need both a ticket and an ID to enter a concert.
2. OR (||
)
The ||
operator returns true
if at least one of the conditions is true. It only returns false
if both are false.
let isAdmin = false;
let isModerator = true;
if (isAdmin || isModerator) {
console.log("You can edit posts");
} else {
console.log("You cannot edit posts");
}
Analogy: You can enter if you have a membership card or a guest pass.
3. NOT (!
)
The !
operator inverts a Boolean value: it turns true
into false
, and vice versa.
let isGuest = false;
if (!isGuest) {
console.log("Welcome back, user!");
}
This means "if not a guest, show welcome message."
Practical Example: Form Validation
let username = "user123";
let password = "pass";
if (username !== "" && password !== "") {
console.log("Form submitted");
} else {
console.log("Please fill in all fields");
}
Here, the form only submits if both username and password are filled.
Summary
Logical operators help combine multiple conditions (&&
, ||
) or reverse a condition (!
). They are fundamental in controlling program flow and building complex decision-making in your JavaScript code.
String concatenation means joining two or more strings together to form one combined string. In JavaScript, you can do this in two main ways: using the +
operator or using template literals.
1. Using the +
Operator
The +
operator joins strings simply by placing them side by side.
let firstName = "Alice";
let lastName = "Johnson";
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: Alice Johnson
Here, we add a space " "
between the first and last names to separate them.
2. Using Template Literals
Template literals (introduced in ES6) allow embedding variables directly inside strings using backticks and
${}` placeholders.
let firstName = "Alice";
let lastName = "Johnson";
let fullName = `${firstName} ${lastName}`;
console.log(fullName); // Output: Alice Johnson
Why Prefer Template Literals?
+
operators.Mini Activity: Create a Greeting Message
Try this yourself:
let userName = "Bob";
let day = "Monday";
let greeting = `Hello, ${userName}! Happy ${day}!`;
console.log(greeting); // Output: Hello, Bob! Happy Monday!
Summary
While the +
operator works well for simple concatenation, template literals make combining strings with variables easier and more readable. Start using template literals to write cleaner, modern JavaScript code!
Operator precedence determines the order in which JavaScript evaluates parts of an expression when multiple operators are used. Just like in math, some operations happen before others unless you use parentheses to change the order.
How JavaScript Evaluates Expressions
For example, multiplication (*
) has higher precedence than addition (+
), so it is evaluated first:
let result = 3 + 4 * 5;
console.log(result); // Outputs 23, not 35
Here, 4 * 5
is calculated first (equals 20), then added to 3.
Using Parentheses to Control Order
You can use parentheses ()
to force certain operations to happen first:
let result = (3 + 4) * 5;
console.log(result); // Outputs 35
Now, 3 + 4
is calculated first (equals 7), then multiplied by 5.
Operator Precedence in Logical Expressions
Logical operators also have precedence. The NOT operator (!
) has higher precedence than AND (&&
) and OR (||
):
let a = true;
let b = false;
console.log(!a && b); // false, because !a is false, then false && false is false
console.log(!(a && b)); // true, parentheses change evaluation order
Why Operator Precedence Matters
Understanding operator precedence helps you predict how complex expressions are evaluated and avoid bugs. When in doubt, use parentheses—they make your code clearer and ensure it runs as intended.
Summary Table (Simplified)
Precedence Level | Operator | Example |
---|---|---|
High | () , ! |
(2 + 3) * 4 |
Medium | * , / , % |
4 * 5 + 2 |
Low | + , - |
3 + 4 * 5 |
Lowest | && , || |
true && false |
Use operator precedence knowledge to write accurate and readable JavaScript expressions!