ลูปพื้นฐานที่สุดใน JavaScript คือลูป while วัตถุประสงค์ของลูป while คือการดำเนินการคำสั่งหรือบล็อกโค้ดซ้ำๆ ตราบใดที่นิพจน์เป็นจริง เมื่อนิพจน์กลายเป็นเท็จ การวนซ้ำจะสิ้นสุดลง
ไวยากรณ์
ไวยากรณ์ของ while loop ใน JavaScript มีดังต่อไปนี้ -
while (expression){
Statement(s) to be executed if expression is true
} ตัวอย่าง
คุณสามารถลองเรียกใช้ตัวอย่างต่อไปนี้เพื่อใช้งาน while loop
การสาธิตสด
<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>