Advertisement
Guest User

Untitled

a guest
Apr 29th, 2017
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. /*
  2. * Loops
  3. *
  4. * loops are blocks of code that is repeated
  5. * they go until a certain condition is met
  6. *
  7. */
  8.  
  9. /* for loop
  10. *
  11. * for(variable; condition; increment) {
  12. * // code to be repeated
  13. * }
  14. *
  15. */
  16.  
  17. for(let i = 0; i < 3; i++) {
  18. console.log(i);
  19. } // -> 0..1..2
  20.  
  21. /* first it sets the variable (let i = 0)
  22.  
  23. * then it checks the condition (i < 3) 0 < 3
  24. * it is, so it will execute the code block (console.log(i))
  25. * after the code block was executed it increments i (i++) i = 1
  26. *
  27. * then it checks the condition (i < 3) 1 < 3
  28. * it is, so it will execute the code block (console.log(i))
  29. * after the code block was executed it increments i (i++) i = 2
  30. *
  31. * then it checks the condition (i < 3) 2 < 3
  32. * it is, so it will execute the code block (console.log(i))
  33. * after the code block was executed it increments i (i++) i = 3
  34. *
  35. * then it checks the condition (i < 3) 3 < 3
  36.  
  37. * it is not true, so the loop ends
  38. */
  39.  
  40.  
  41. // we can quickly loop over the elements of an array with a loop like so:
  42. const arr = [7, 'hi', {}, [], 33];
  43. for(let i = 0; i < arr.length; i++) {
  44. console.log(arr[i]);
  45. }
  46.  
  47. // and in reverse:
  48. for(let i = arr.length-1; i >= 0; i--) {
  49. console.log(arr[i]);
  50. }
  51.  
  52.  
  53. /* for in loop
  54. * designed for looping for objects
  55. *
  56. * for(variable in object) {
  57. * console.log(variable); // logs the key
  58. * console.log(object[variable]); // logs the value
  59. * }
  60. */
  61.  
  62. const person = {
  63. name: 'cain',
  64. id: 234,
  65. isHuman: true
  66. };
  67.  
  68. for(let key in person) {
  69. console.log(key + ': ' + person[key]);
  70. } // -> name: cain..id: 234..isHuman: true
  71.  
  72.  
  73. /* while loop
  74. *
  75. * a while loop runs until the condition is met
  76. *
  77. * while(condition) {
  78. * // code to be executed
  79. * }
  80. */
  81. let x = 8;
  82. while(x < 12) {
  83. console.log(x);
  84. x++;
  85. } // -> 8..9..10..11
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement