Skip to content

Flow Control ใน JavaScript

สรุปสำคัญ

Flow Control ใน JavaScript แบ่งออกเป็น 2 ประเภทหลัก:

  • Conditional Flow: ควบคุมการทำงานตามเงื่อนไข (if-else, switch)
  • Unconditional Flow: ควบคุมการทำงานโดยตรง (break, continue, return)

การควบคุมแบบมีเงื่อนไข (Conditional Flow)

1. การตรวจสอบเงื่อนไขพื้นฐาน

if-else Statement

ใช้ตรวจสอบเงื่อนไขและดำเนินการตามผลลัพธ์ที่ได้

if-else.js
js
const temperature = 25;
let weatherAdvice;

if (temperature > 30) {
  weatherAdvice = "It's hot! Stay hydrated.";
} else if (temperature > 20) {
  weatherAdvice = "It's a pleasant day.";
} else {
  weatherAdvice = "It's a bit chilly. Bring a jacket.";
}

console.log(weatherAdvice); // Output: "It's a pleasant day."

switch Statement

เหมาะสำหรับการเปรียบเทียบค่าที่แน่นอน หลายๆ กรณี

switch.js
js
const fruitType = "apple";
let fruitDescription;

switch (fruitType) {
  case "apple":
    fruitDescription = "Round and sweet";
    break;
  case "banana":
    fruitDescription = "Long and yellow";
    break;
  case "orange":
    fruitDescription = "Round and citrusy";
    break;
  default:
    fruitDescription = "Unknown fruit";
}

console.log(`The ${fruitType} is ${fruitDescription}.`);

เลือกใช้ให้เหมาะสม

  • if-else: เหมาะกับเงื่อนไขที่ซับซ้อนหรือมีช่วงของค่า
  • switch: เหมาะกับการเปรียบเทียบค่าที่แน่นอนหลายกรณี

2. Operators สำหรับเงื่อนไข

Ternary Operator (? 😃

เขียนเงื่อนไขแบบสั้นในบรรทัดเดียว

ternary.js
js
// แบบพื้นฐาน
const isRaining = true;
const activity = isRaining ? "Stay inside" : "Go for a walk";

// แบบซ้อนหลายเงื่อนไข
const temperature = 28;
const weatherAdvice = temperature > 30
  ? "It's hot!"
  : temperature > 20
  ? "It's pleasant"
  : "It's cool";

Logical Operators (&& และ ||)

ใช้รวมหลายเงื่อนไขเข้าด้วยกัน

logical-operators.js
js
const hasTicket = true;
const hasPassport = true;
const canTravel = hasTicket && hasPassport;

const isWeekend = false;
const isHoliday = true;
const canRelax = isWeekend || isHoliday;

Nullish Coalescing (??) และ Optional Chaining (?.)

ช่วยจัดการค่า null/undefined อย่างปลอดภัย

modern-operators.js
js
// Nullish Coalescing
const userPreference = null;
const theme = userPreference ?? "light";

// Optional Chaining
const user = {
  address: { city: "Bangkok" },
};
const city = user.address?.city;

การควบคุมแบบไม่มีเงื่อนไข (Unconditional Flow)

1. การควบคุมลูป

break Statement

หยุดการทำงานของลูปทันที

break.js
js
const numbers = [1, 2, 3, 4, 5];
let sum = 0;

for (let num of numbers) {
  if (sum > 10) break;
  sum += num;
}

continue Statement

ข้ามการทำงานในรอบปัจจุบัน

continue.js
js
const numbers = [1, 2, 3, 4, 5];
let sumOfEven = 0;

for (let num of numbers) {
  if (num % 2 !== 0) continue;
  sumOfEven += num;
}

2. การควบคุมฟังก์ชัน

return Statement

ส่งค่ากลับและจบการทำงานของฟังก์ชัน

return.js
js
function calculateDiscount(price, discountPercentage) {
  if (discountPercentage < 0 || discountPercentage > 100) {
    return "Invalid discount percentage";
  }
  return price - (price * discountPercentage / 100);
}

throw Statement

ส่งข้อผิดพลาดและหยุดการทำงาน

throw.js
js
function divide(a, b) {
  if (b === 0) {
    throw new Error("Division by zero is not allowed");
  }
  return a / b;
}

try {
  console.log(divide(10, 0));
} catch (error) {
  console.error(error.message);
}

// try-catch-finally
try {
  throw new Error("เกิดข้อผิดพลาดขึ้น");
} catch (error) {
  console.error(error.message);
} finally {
  console.log("ทำงานเสมอไม่ว่าจะเกิดข้อผิดพลาดหรือไม่");
}

yield Statement

หยุดการทำงานชั่วคราวใน Generator

yield.js
js
function* numberGenerator() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = numberGenerator();
console.log(gen.next().value); // 1

แนวทางการใช้งาน

  • ใช้ break เมื่อต้องการหยุดการทำงานของลูปทันที
  • ใช้ continue เมื่อต้องการข้ามการทำงานในรอบปัจจุบัน
  • ใช้ return เมื่อต้องการส่งค่ากลับจากฟังก์ชัน
  • ใช้ throw เมื่อต้องการแจ้งข้อผิดพลาด
  • ใช้ yield เมื่อต้องการสร้าง iterator แบบกำหนดเอง

Array Methods สำหรับการควบคุมการทำงาน

Array Methods ใน JavaScript ช่วยให้เราจัดการกับข้อมูลใน array ได้อย่างมีประสิทธิภาพ โดยไม่ต้องเขียนลูปเอง

array-methods.js
js
const numbers = [1, 2, 3, 4, 5];

// forEach - ทำงานกับทุกสมาชิกใน array
numbers.forEach(num => console.log(num * 2));

// map - สร้าง array ใหม่จากการแปลงค่า
const doubled = numbers.map(num => num * 2);

// filter - กรองสมาชิกตามเงื่อนไข
const evenNumbers = numbers.filter(num => num % 2 === 0);

// reduce - รวมค่าทั้งหมดเป็นค่าเดียว
const sum = numbers.reduce((total, num) => total + num, 0);

// some - ตรวจสอบว่ามีสมาชิกที่ตรงเงื่อนไขหรือไม่
const hasEven = numbers.some(num => num % 2 === 0);

// every - ตรวจสอบว่าทุกสมาชิกตรงเงื่อนไขหรือไม่
const allPositive = numbers.every(num => num > 0);

ข้อดีของ Array Methods

  • ลดความซับซ้อนของโค้ด
  • ทำให้โค้ดอ่านง่ายและเข้าใจง่ายขึ้น
  • ลดโอกาสเกิดข้อผิดพลาดจากการเขียนลูปเอง

การจัดการข้อผิดพลาด (Error Handling)

การจัดการข้อผิดพลาดช่วยให้โปรแกรมทำงานต่อไปได้แม้เกิดข้อผิดพลาด :::