Operators
Operators
Section titled “Operators”Arithmetic Operators
Section titled “Arithmetic Operators”const a = 10, b = 3;
console.log(a + b); // 13 — additionconsole.log(a - b); // 7 — subtractionconsole.log(a * b); // 30 — multiplicationconsole.log(a / b); // 3.333... — division (ไม่มี integer division)console.log(a % b); // 1 — modulus (เศษ)console.log(a ** b); // 1000 — exponentiation
// increment / decrementlet count = 0;count++; // 1count--; // 0a, b = 10, 3print(a // b) # 3 — integer divisionprint(a ** b) # 1000int a = 10, b = 3;printf("%d", a / b); // 3 — integer division อัตโนมัติprintf("%d", a % b); // 1SELECT 10 / 3; -- 3 (integer division)SELECT 10 % 3; -- 1SELECT POWER(10, 3); -- 1000Comparison: == vs ===
Section titled “Comparison: == vs ===”นี่คือจุดที่สำคัญที่สุดใน JavaScript operators:
// == (loose equality) — แปลง type ก่อนเทียบ ❌console.log(5 == "5"); // true ⚠️console.log(0 == false); // true ⚠️console.log(null == undefined); // true ⚠️
// === (strict equality) — เทียบทั้ง value และ type ✅console.log(5 === "5"); // false ✅console.log(0 === false); // false ✅console.log(null === undefined); // false ✅Logical Operators
Section titled “Logical Operators”const age = 25;const hasLicense = true;
// AND — ทั้งสองต้อง trueif (age >= 18 && hasLicense) { /* ขับรถได้ */ }
// OR — อย่างน้อยหนึ่งต้อง trueif (age < 13 || age > 65) { /* ส่วนลดพิเศษ */ }
// NOT — กลับค่าif (!hasLicense) { /* ไม่มีใบขับขี่ */ }Ternary Operator
Section titled “Ternary Operator”const age = 20;const status = age >= 18 ? "ผู้ใหญ่" : "เด็ก";// เทียบเท่า:// if (age >= 18) { status = "ผู้ใหญ่"; } else { status = "เด็ก"; }Nullish Coalescing (??)
Section titled “Nullish Coalescing (??)”// ?? คืนค่าขวาเมื่อซ้ายเป็น null หรือ undefined เท่านั้นconst input = null;const value = input ?? "default"; // "default"
// เปรียบเทียบกับ || ที่จับ falsy ทั้งหมดconst count = 0;console.log(count || 10); // 10 ⚠️ (0 เป็น falsy)console.log(count ?? 10); // 0 ✅ (0 ไม่ใช่ null/undefined)Optional Chaining + Nullish Coalescing
Section titled “Optional Chaining + Nullish Coalescing”const user = { profile: null };
// รวม ?. กับ ?? เพื่อ safe access + defaultconst name = user.profile?.name ?? "ไม่ระบุชื่อ";console.log(name); // "ไม่ระบุชื่อ"