Module 2: Language Fundamentals
Operators and Expressions
Use arithmetic, comparison, logical, assignment, and conditional operators.
Operators combine values or perform an action. Arithmetic operators include +, -, *, /, %, and **. Assignment operators such as += update a binding. Comparison operators produce booleans.
const subtotal = 1200;
const discountRate = 0.1;
const total = subtotal - subtotal * discountRate;
console.log(total); // 1080
console.log(total >= 1000); // true
Logical operators#
&& returns the first falsy operand or the last operand if all are truthy. || returns the first truthy operand or the last operand. They short-circuit, meaning the second expression may not run. ! negates truthiness.
const username = "swagat";
const displayName = username || "Guest";
const isEligible = true;
const canSubmit = isEligible && total > 0;
For a fallback that should apply only when the left side is null or undefined, use ?? rather than ||:
const pageSize = 0 ?? 20; // 0
const fallbackSize = 0 || 20; // 20
Conditional expression#
const status = total > 1000 ? "large order" : "regular order";
Ternaries are useful for short choices. Use if/else when the logic has multiple steps or is hard to read inline.
Precedence#
Operators have precedence rules, but excessive reliance on precedence makes code harder to understand. Add parentheses when they improve clarity, such as const average = (a + b) / 2.
Practice#
Calculate a discounted price, then use a comparison and a conditional expression to label the order.