หัวข้อ 3: โครงสร้างควบคุม if/else, switch, for, while, for...of, for...in

คำจำกัดความ

โครงสร้างควบคุม (Control Flow) คือคำสั่งที่กำหนดทิศทางการทำงานของโปรแกรม เช่น เลือกทำตามเงื่อนไขหรือวนซ้ำหลายครั้ง

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#458588", "primaryTextColor": "#fbf1c7", "primaryBorderColor": "#fabd2f", "lineColor": "#a89984", "secondaryColor": "#b8bb26", "tertiaryColor": "#d3869b", "background": "#282828", "mainBkg": "#3c3836", "textColor": "#ebdbb2"}}}%%
flowchart TD
  A["Start
เริ่มโปรแกรม"] --> B{"Condition?
เงื่อนไขจริงไหม"} B -- "true / จริง" --> C["Run block A
ทำงานชุด A"] B -- "false / เท็จ" --> D["Run block B
ทำงานชุด B"] C --> E["Loop?
ต้องวนซ้ำไหม"] D --> E E -- "yes / ใช่" --> B E -- "no / ไม่" --> F["End
จบโปรแกรม"]

if / else if / else

const score = 82;

if (score >= 80) {
  console.log("เกรด A");
} else if (score >= 70) {
  console.log("เกรด B");
} else if (score >= 60) {
  console.log("เกรด C");
} else {
  console.log("ต้องปรับปรุง");
}

Ternary Operator

Ternary Operator ใช้เขียนเงื่อนไขสั้น ๆ

const score = 65;
const result = score >= 50 ? "ผ่าน" : "ไม่ผ่าน";
console.log(result);

Nullish Coalescing ??

?? คืนค่าด้านขวาเมื่อค่าด้านซ้ายเป็น null หรือ undefined

const nickname = null;
const displayName = nickname ?? "ไม่ระบุชื่อ";
console.log(displayName); // ไม่ระบุชื่อ

Optional Chaining ?.

?. ใช้เข้าถึง property โดยไม่ error เมื่อค่าก่อนหน้าเป็น null หรือ undefined

const user = { profile: { email: "ana@example.com" } };
console.log(user.profile?.email); // ana@example.com
console.log(user.address?.city); // undefined

switch/case

const role = "teacher";

switch (role) {
  case "student":
    console.log("เข้าสู่หน้าผู้เรียน");
    break;
  case "teacher":
    console.log("เข้าสู่หน้าผู้สอน");
    break;
  default:
    console.log("ไม่พบสิทธิ์ผู้ใช้");
}

Loop

for

for (let i = 0; i < 3; i++) {
  console.log(`รอบที่ ${i + 1}`);
}

while

let count = 0;

while (count < 3) {
  console.log(count);
  count += 1;
}

for...of

const lessons = ["HTML", "CSS", "JavaScript"];

for (const lesson of lessons) {
  console.log(lesson);
}

for...in

const user = { name: "Ana", age: 20 };

for (const key in user) {
  console.log(`${key}: ${user[key]}`);
}

ตารางเปรียบเทียบ Loop

Loop เหมาะกับ ตัวอย่างข้อมูล
for ต้องการ index array, จำนวนรอบแน่นอน
while วนจนเงื่อนไขเป็นเท็จ polling, retry
for...of วนผ่านค่า array, string
for...in วนผ่าน key object

สมการจำนวนรอบของ for

rounds = end-start step

โดยที่ rounds คือจำนวนรอบโดยประมาณ, start คือค่าเริ่มต้น, end คือค่าปลายทาง, และ step คือค่าที่เพิ่มหรือลดในแต่ละรอบ

แบบทดสอบหลังเรียน

  1. Ternary operator เหมาะกับเงื่อนไขแบบใด
  2. ?? ต่างจาก || อย่างไรในแนวคิด
  3. Optional chaining ป้องกัน error แบบใด
  4. switch ควรมี break เพราะอะไร
  5. for...of และ for...in ต่างกันอย่างไร

กลับสัปดาห์ที่ 4