คำสั่ง while เป็น ลูปพื้นฐานที่สุด ใน JavaScript ใช้เพื่อ รันโค้ดซ้ำไปเรื่อยๆ ตราบใดที่เงื่อนไขยังเป็น true (Pre-test Loop - ตรวจสอบก่อนรันทุกรอบ)
ไวยากรณ์
while (condition) {
// โค้ดที่จะรันซ้ำ
}
ตัวอย่างโค้ด
<html>
<body>
<script>
var count = 0;
document.write("Starting Loop ");
while (count < 10) {
document.write("Current Count: " + count + "<br/>");
count++;
}
document.write("Loop stopped!");
</script>
</body>
</html>
ผลลัพธ์
Starting Loop Current Count: 0 Current Count: 1 ... Current Count: 9 Loop stopped!
โครงสร้างการทำงาน
- ตรวจสอบ
condition - ถ้า true: รัน Body → กลับไป 1.
- ถ้า false: ออกจากลูป ทำคำสั่งต่อไป
ตัวอย่างการใช้งานทั่วไป
1. นับเลข / Iterate ด้วย Index
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
2. ประมวลผลจนกว่าจะหมด (เช่น Stack, Queue)
const stack = [1, 2, 3, 4, 5];
while (stack.length > 0) {
const item = stack.pop();
console.log(item); // 5, 4, 3, 2, 1
}
3. รอเงื่อนไข (Polling / Retry)
let ready = false;
let attempts = 0;
while (!ready && attempts < 10) {
ready = checkReady();
attempts++;
await sleep(100);
}
4. อ่านข้อมูล Stream/Iterator
const reader = stream.getReader();
let result;
while (!(result = await reader.read()).done) {
processChunk(result.value);
}
while vs for
| ลักษณะ | while | for |
|---|---|---|
| เหมาะกับ | เงื่อนไขซับซ้อน ไม่รู้จำนวนรอบ | รู้จำนวนรอบ / ตัวนับชัดเจน |
| Initialization | นอกลูป | ในหัวลูป |
| Iteration | ในบล็อก (Manual) | ในหัวลูป (Auto) |
| Scope ตัวแปร | กว้างกว่า (ถ้าใช้ var) | จำกัดในลูป (ถ้าใช้ let) |
ข้อควรระวัง
- Infinite Loop: เงื่อนไขไม่เคย false → โปรแกรมค้าง (ต้องมี Logic เปลี่ยนเงื่อนไขในบล็อก)
- Off-by-one: ตรวจสอบเงื่อนไขขอบเขตให้ถูกต้อง
- ใช้
letสำหรับตัวนับ เพื่อจำกัด Scope - หลีกเลี่ยงการทำงานหนักใน Condition (เรียก Function ซับซ้อน)
แปลงระหว่าง while และ for
// while → for
let i = 0;
while (i < 10) { body; i++; }
// เทียบเท่า
for (let i = 0; i < 10; i++) { body; }
// for → while
for (let i = 0; i < 10; i++) { body; }
// เทียบเท่า
let i = 0;
while (i < 10) { body; i++; }