Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Loops
- *
- * loops are blocks of code that is repeated
- * they go until a certain condition is met
- *
- */
- /* for loop
- *
- * for(variable; condition; increment) {
- * // code to be repeated
- * }
- *
- */
- for(let i = 0; i < 3; i++) {
- console.log(i);
- } // -> 0..1..2
- /* first it sets the variable (let i = 0)
- * then it checks the condition (i < 3) 0 < 3
- * it is, so it will execute the code block (console.log(i))
- * after the code block was executed it increments i (i++) i = 1
- *
- * then it checks the condition (i < 3) 1 < 3
- * it is, so it will execute the code block (console.log(i))
- * after the code block was executed it increments i (i++) i = 2
- *
- * then it checks the condition (i < 3) 2 < 3
- * it is, so it will execute the code block (console.log(i))
- * after the code block was executed it increments i (i++) i = 3
- *
- * then it checks the condition (i < 3) 3 < 3
- * it is not true, so the loop ends
- */
- // we can quickly loop over the elements of an array with a loop like so:
- const arr = [7, 'hi', {}, [], 33];
- for(let i = 0; i < arr.length; i++) {
- console.log(arr[i]);
- }
- // and in reverse:
- for(let i = arr.length-1; i >= 0; i--) {
- console.log(arr[i]);
- }
- /* for in loop
- * designed for looping for objects
- *
- * for(variable in object) {
- * console.log(variable); // logs the key
- * console.log(object[variable]); // logs the value
- * }
- */
- const person = {
- name: 'cain',
- id: 234,
- isHuman: true
- };
- for(let key in person) {
- console.log(key + ': ' + person[key]);
- } // -> name: cain..id: 234..isHuman: true
- /* while loop
- *
- * a while loop runs until the condition is met
- *
- * while(condition) {
- * // code to be executed
- * }
- */
- let x = 8;
- while(x < 12) {
- console.log(x);
- x++;
- } // -> 8..9..10..11
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement