โครงสร้างควบคุม (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 / elseconst 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 ใช้เขียนเงื่อนไขสั้น ๆ
const score = 65;
const result = score >= 50 ? "ผ่าน" : "ไม่ผ่าน";
console.log(result);
???? คืนค่าด้านขวาเมื่อค่าด้านซ้ายเป็น null หรือ undefined
const nickname = null;
const displayName = nickname ?? "ไม่ระบุชื่อ";
console.log(displayName); // ไม่ระบุชื่อ
?.?. ใช้เข้าถึง 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/caseconst role = "teacher";
switch (role) {
case "student":
console.log("เข้าสู่หน้าผู้เรียน");
break;
case "teacher":
console.log("เข้าสู่หน้าผู้สอน");
break;
default:
console.log("ไม่พบสิทธิ์ผู้ใช้");
}
forfor (let i = 0; i < 3; i++) {
console.log(`รอบที่ ${i + 1}`);
}
whilelet count = 0;
while (count < 3) {
console.log(count);
count += 1;
}
for...ofconst lessons = ["HTML", "CSS", "JavaScript"];
for (const lesson of lessons) {
console.log(lesson);
}
for...inconst user = { name: "Ana", age: 20 };
for (const key in user) {
console.log(`${key}: ${user[key]}`);
}
| Loop | เหมาะกับ | ตัวอย่างข้อมูล |
|---|---|---|
for |
ต้องการ index | array, จำนวนรอบแน่นอน |
while |
วนจนเงื่อนไขเป็นเท็จ | polling, retry |
for...of |
วนผ่านค่า | array, string |
for...in |
วนผ่าน key | object |
forโดยที่ rounds คือจำนวนรอบโดยประมาณ, start คือค่าเริ่มต้น, end คือค่าปลายทาง, และ step คือค่าที่เพิ่มหรือลดในแต่ละรอบ
?? ต่างจาก || อย่างไรในแนวคิดswitch ควรมี break เพราะอะไรfor...of และ for...in ต่างกันอย่างไร