Week 2: Mastering Variables, Data, and Operations in JS
Unlocking the power to store and manipulate information in JavaScript.
Dive into Chapter 2Arithmetic Operators: Performing Calculations.
These operators perform mathematical calculations on numbers.
| Operator | Name | Example | Result | Description |
|---|---|---|---|---|
| + | Addition | 5 + 3 | 8 | Adds operands. |
| - | Subtraction | 5 - 3 | 2 | Subtracts right operand from left. |
| * | Multiplication | 5 * 3 | 15 | Multiplies operands. |
| / | Division | 5 / 3 | 1.666... | Divides left operand by right. |
| % | Modulo (Remainder) | 5 % 3 | 2 | Returns the remainder of a division. |
| ** | Exponentiation (ES7+) | 5 ** 3 | 125 | Raises left operand to the power of the right. |
| ++ | Increment | let x=5; x++; | x is 6 | Increases operand by 1 (postfix/prefix). |
| -- | Decrement | let y=5; y--; | y is 4 | Decreases operand by 1 (postfix/prefix). |
Examples:
let a = 10;
let b = 4;
console.log("a + b =", a + b); // 14
console.log("a / b =", a / b); // 2.5
console.log("a % b =", a % b); // 2
console.log("a ** b =", a ** b); // 10000
let counter = 5;
counter++; // counter is now 6
console.log("Counter:", counter);
The + operator can also be used for string concatenation:
let firstName = "Jane";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // "Jane Doe"
console.log(fullName);
Logical Operators: Combining Boolean Expressions.
Logical operators combine or invert boolean values.
- && (Logical AND): Returns true if both operands are true (or truthy). Otherwise returns false (or the first falsy value encountered).
let isAdult = true; let hasTicket = false; console.log(isAdult && hasTicket); // false - || (Logical OR): Returns true if at least one operand is true (or truthy). Returns false (or the last falsy value) only if both are false (or falsy).
let isWeekend = true; let isHoliday = false; console.log(isWeekend || isHoliday); // true - ! (Logical NOT): Inverts the boolean value of its operand. !true becomes false, and !false becomes true.
let isRaining = false; console.log(!isRaining); // true
JavaScript also uses the concept of "truthy" and "falsy" values in logical operations. Falsy values include false, 0, "" (empty string), null, undefined, and NaN. All other values are considered truthy.
Operator Precedence
JavaScript operators have a specific order of precedence (similar to mathematical rules). For example, multiplication (*) happens before addition (+), and logical AND (&&) happens before logical OR (||). Use parentheses () to control the order of evaluation explicitly when needed.
let result = 10 + 5 * 2; // 20 (multiplication first)
let result2 = (10 + 5) * 2; // 30 (parentheses first)
let check = true || false && false; // true (&& has higher precedence than ||)
let check2 = (true || false) && false; // false (parentheses first)