PageRenderTime 50ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/loops/while.md

https://github.com/turbol/javascript
Markdown | 62 lines | 45 code | 17 blank | 0 comment | 0 complexity | 8eeb7395796eda782b2c9804807bf72f MD5 | raw file
Possible License(s): Apache-2.0
  1. # While Loop
  2. While Loops repetitively execute a block of code as long as a specified condition is true.
  3. ```javascript
  4. while(condition){
  5. // do it as long as condition is true
  6. }
  7. ```
  8. For example, the loop in this example will repetitively execute its block of code as long as the variable i is less than 5:
  9. ```javascript
  10. var i = 0, x = "";
  11. while (i < 5) {
  12. x = x + "The number is " + i;
  13. i++;
  14. }
  15. ```
  16. The Do/While Loop is a variant of the while loop. This loop will execute the code block once before checking if the condition is true. It then repeats the loop as long as the condition is true:
  17. ```javascript
  18. do {
  19. // code block to be executed
  20. } while (condition);
  21. ```
  22. **Note**: Be careful to avoid infinite looping if the condition is always true!
  23. ---
  24. Using a while-loop, create a variable named `message` that equals the concatenation of integers (0, 1, 2, ...) as long as its length (`message.length`) is less than 100.
  25. ```js
  26. var message = "";
  27. ```
  28. ```js
  29. var message = "";
  30. var i = 0;
  31. while (message.length < 100) {
  32. message = message + i;
  33. i = i + 1;
  34. }
  35. ```
  36. ```js
  37. var message2 = "";
  38. var i2 = 0;
  39. while (message2.length < 100) {
  40. message2 = message2 + i2;
  41. i2 = i2 + 1;
  42. }
  43. assert(message === message2);
  44. ```
  45. ---