The first two days covered JavaScript basics, development environment setup, variables and data types. Today will dive deep into JavaScript operators and expressions, which are fundamental for data manipulation and logical calculations. Mastering operator usage is crucial for writing complex program logic.
📚 Today's Learning Objectives
- Master JavaScript's various operators
- Understand operator precedence and associativity
- Learn to use expressions for calculations
- Understand special operator usage
🔢 Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations:
let a = 10;
let b = 3;
// Basic arithmetic operations
console.log(a + b); // 13 (addition)
console.log(a - b); // 7 (subtraction)
console.log(a * b); // 30 (multiplication)
console.log(a / b); // 3.3333333333333335 (division)
console.log(a % b); // 1 (modulus)
console.log(a ** b); // 1000 (exponentiation, ES2016)
// Increment and decrement
let x = 5;
console.log(++x); // 6 (pre-increment)
console.log(x++); // 6 (post-increment, returns original value)
console.log(x); // 7
let y = 5;
console.log(--y); // 4 (pre-decrement)
console.log(y--); // 4 (post-decrement, returns original value)
console.log(y); // 3
String Operations
// String concatenation
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + lastName; // "JohnDoe"
// Numbers and strings
console.log("5" + 3); // "53" (string concatenation)
console.log("5" - 3); // 2 (numeric operation)
console.log("5" * 3); // 15 (numeric operation)
console.log("5" / 3); // 1.6666666666666667 (numeric operation)
⚖️ Comparison Operators
Comparison operators are used to compare the size relationship between two values:
let a = 10;
let b = 5;
let c = "10";
// Basic comparison
console.log(a > b); // true
console.log(a < b); // false
console.log(a >= b); // true
console.log(a <= b); // false
// Equality comparison
console.log(a == c); // true (value equal, different types)
console.log(a === c); // false (value and type both equal)
console.log(a != c); // false (value not equal)
console.log(a !== c); // true (value or type not equal)
Strict Equality vs Loose Equality
// Loose equality (==) - performs type conversion
console.log(5 == "5"); // true
console.log(true == 1); // true
console.log(false == 0); // true
console.log(null == undefined); // true
console.log("" == 0); // true
// Strict equality (===) - no type conversion
console.log(5 === "5"); // false
console.log(true === 1); // false
console.log(false === 0); // false
console.log(null === undefined); // false
console.log("" === 0); // false
// Recommended to use strict equality
🧠 Logical Operators
Logical operators are used to combine and manipulate boolean values:
let isStudent = true;
let hasJob = false;
let age = 20;
// Logical AND (&&)
console.log(isStudent && age > 18); // true
console.log(isStudent && hasJob); // false
// Logical OR (||)
console.log(isStudent || hasJob); // true
console.log(hasJob || age < 18); // false
// Logical NOT (!)
console.log(!isStudent); // false
console.log(!hasJob); // true
Short-circuit Evaluation
// && short-circuit: if first is false, second won't execute
let result1 = false && console.log("This won't execute");
let result2 = true && console.log("This will execute"); // Output: "This will execute"
// || short-circuit: if first is true, second won't execute
let result3 = true || console.log("This won't execute");
let result4 = false || console.log("This will execute"); // Output: "This will execute"
// Practical application: default value setting
let userName = "";
let displayName = userName || "Anonymous User"; // "Anonymous User"
let userAge = 0;
let validAge = userAge || 18; // 18 (note: 0 is considered falsy)
let betterAge = userAge ?? 18; // 0 (nullish coalescing operator, only effective for null/undefined)
📝 Assignment Operators
Assignment operators are used to assign values to variables:
let x = 10;
// Basic assignment
x = 20; // x is now 20
// Compound assignment
x += 5; // x = x + 5, x is now 25
x -= 3; // x = x - 3, x is now 22
x *= 2; // x = x * 2, x is now 44
x /= 4; // x = x / 4, x is now 11
x %= 3; // x = x % 3, x is now 2
console.log(x); // 2
🎯 Special Operators
Ternary Operator (Conditional Operator)
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"
// Nested ternary operators
let score = 85;
let grade =
score >= 90
? "A"
: score >= 80
? "B"
: score >= 70
? "C"
: score >= 60
? "D"
: "F";
console.log(grade); // "B"
Nullish Coalescing Operator (??)
let userName = null;
let displayName = userName ?? "Anonymous User"; // "Anonymous User"
let userAge = 0;
let age = userAge ?? 18; // 0 (because 0 is not null or undefined)
// Difference from ||
let count = 0;
let result1 = count || 10; // 10 (0 is considered falsy)
let result2 = count ?? 10; // 0 (only null/undefined will use default value)
Optional Chaining Operator (?.)
let user = {
name: "John",
address: {
city: "New York",
street: "Broadway",
},
};
// Safe access to nested properties
console.log(user?.name); // "John"
console.log(user?.address?.city); // "New York"
console.log(user?.phone?.number); // undefined (no error)
// Combined with function calls
let obj = {
method: function () {
return "Hello";
},
};
console.log(obj?.method?.()); // "Hello"
console.log(obj?.nonExistent?.()); // undefined
📊 Operator Precedence
Operator precedence determines the execution order of operations in expressions:
// Precedence from high to low
let result = 2 + 3 * 4; // 14 (not 20)
console.log(result);
// Use parentheses to change precedence
let result2 = (2 + 3) * 4; // 20
console.log(result2);
// Complex expressions
let a = 1,
b = 2,
c = 3;
let complex = a + b * c ** 2; // 1 + 2 * 9 = 19
console.log(complex);
let withParentheses = (a + b) * c ** 2; // 3 * 9 = 27
console.log(withParentheses);
Common Operator Precedence (High to Low)
-
()
- Grouping -
++
--
- Increment/Decrement -
!
- Logical NOT -
**
- Exponentiation -
*
/
%
- Multiplication/Division/Modulus -
+
-
- Addition/Subtraction -
<
<=
>
>=
- Comparison -
==
!=
===
!==
- Equality -
&&
- Logical AND -
||
- Logical OR -
??
- Nullish Coalescing -
? :
- Ternary Operator -
=
- Assignment
🎯 Practice Exercises
Exercise 1: Calculator Program
function calculator(a, b, operation) {
switch (operation) {
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return b !== 0 ? a / b : "Error: Cannot divide by zero";
case "%":
return b !== 0 ? a % b : "Error: Cannot divide by zero";
case "**":
return a ** b;
default:
return "Unsupported operation";
}
}
// Test calculator
console.log(calculator(10, 3, "+")); // 13
console.log(calculator(10, 3, "-")); // 7
console.log(calculator(10, 3, "*")); // 30
console.log(calculator(10, 3, "/")); // 3.3333333333333335
console.log(calculator(10, 3, "%")); // 1
console.log(calculator(10, 3, "**")); // 1000
console.log(calculator(10, 0, "/")); // "Error: Cannot divide by zero"
Exercise 2: Grade Rating System
function getGrade(score) {
if (typeof score !== "number" || score < 0 || score > 100) {
return "Invalid score";
}
return score >= 90
? "A"
: score >= 80
? "B"
: score >= 70
? "C"
: score >= 60
? "D"
: "F";
}
// Test grade system
let scores = [95, 85, 75, 65, 55, 105, -5, "abc"];
scores.forEach((score) => {
console.log(`Score ${score}: ${getGrade(score)}`);
});
Exercise 3: User Information Validation
function validateUser(user) {
// Use optional chaining and nullish coalescing
let name = user?.name ?? "Not provided";
let age = user?.age ?? 0;
let email = user?.email ?? "Not provided";
// Validation logic
let isValidName = name !== "Not provided" && name.length >= 2;
let isValidAge = age >= 18 && age <= 120;
let isValidEmail = email !== "Not provided" && email.includes("@");
return {
name: name,
age: age,
email: email,
isValid: isValidName && isValidAge && isValidEmail,
errors: [
!isValidName ? "Invalid name" : null,
!isValidAge ? "Invalid age" : null,
!isValidEmail ? "Invalid email" : null,
].filter((error) => error !== null),
};
}
// Test user validation
let users = [
{ name: "John", age: 25, email: "john@example.com" },
{ name: "Jane", age: 17, email: "jane@example.com" },
{ name: "Bob", age: 30 },
{ age: 25, email: "invalid-email" },
{},
];
users.forEach((user, index) => {
let result = validateUser(user);
console.log(`User ${index + 1}:`, result);
});
🔍 Today's Key Points Summary
- Arithmetic Operators: Basic mathematical operations and string operations
- Comparison Operators: Difference between strict equality and loose equality
- Logical Operators: Short-circuit evaluation and practical applications
- Assignment Operators: Compound assignment usage
- Special Operators: Ternary operator, nullish coalescing, optional chaining
- Operator Precedence: Understanding operation order importance
📚 Tomorrow's Preview
Tomorrow will learn about conditional statements and logical control, including:
- if/else statements
- switch statements
- conditional judgment best practices
- logical control flow
💡 Learning Tips
- Understand Precedence: Remember common operator precedence order
-
Use Strict Equality: Recommend using
===
instead of==
-
Master Short-circuit: Understand
&&
and||
short-circuit characteristics - Use Special Operators: Ternary operator, nullish coalescing, etc. make code more concise
This concludes the introduction to day three's learning content. Tomorrow will continue learning about conditional statements and logical control.
Top comments (0)