Understanding JavaScript While Loops
While loops in JavaScript repeatedly execute a block of code as long as a specified condition is true. This article covers the syntax, examples, and differences between while and do-while loops. Dive into JavaScript looping constructs to enhance your programming skills.
Download Presentation
Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
E N D
Presentation Transcript
while Syntax The while loop loops through a block of code as long as a specified condition is true. while (condition) { code block to be executed; }
i i < 10 condition is tested, if TRUE, code block executed increment while Syntax i = 0 0 < 10 TRUE i = i + 1 0 + 1 <script> var text = ""; var i = 0; i = 1 1 < 10 TRUE i = i + 1 1 + 1 i = 2 2 < 10 TRUE i = i + 1 2 + 1 i = 3 3 < 10 TRUE i = i + 1 3 + 1 i = 4 4 < 10 TRUE i = i + 1 4 + 1 i = 5 5 < 10 TRUE i = i + 1 5 + 1 while (i < 10) { text += "<br>The number is " + i; i++; } document.getElementById("demo").innerHTML = text; </script> i = 6 6 < 10 TRUE i = i + 1 6 + 1 i = 7 7 < 10 TRUE i = i + 1 7 + 1 i = 8 8 < 10 TRUE i = i + 1 8 + 1 i = 9 9 < 10 TRUE i = i + 1 9 + 1 i = 10 10 < 10 FALSE Loop stops
do while Syntax Loop will execute the code block once, before checking if the condition is true do { code block to be executed } while (condition);
do while Syntax The do while loop code executes at least once as long then continues if condition is true. <script> var text = "" var i = 0; do { text += "<br>The number is " + i; i++; } while (i < 10); document.getElementById("demo").innerHTML = text; </script>
Test Yourself With Exercises JS While Loops In the W3Schools Tutorial, complete Exercise