Session 7

Advanced Javascript

loops

16. Nov. 2022, 17:00-18:30

Artful Coding 1: web-based games development

dieAngewandte

(allmost) all you need to know about loops

Loops and iteration @ MDN web docs

Loops (the old way)


            var i = 0;
            while (i < 100) {
              console.log(i)
              i++
            }

            for (var i=0; i<100; i++) {
              console.log(i)
            }
          

Loops on arrays (the ES5 way)


            const numbers = [1, 2, 1, 2, 3, 4];
            let rhythm = "and counting ";

            function addRhythmCounter(number) {
              console.log(number);
              rhythm += number + ", and ";
            }

            numbers.forEach(addRhythmCounter);

            console.log(rhythm);
          

Array.prototype.forEach() @ MDN web docs

Looping through object properties

And only object properties! Do not use this on arrays!


            let someOne = {
              firstname: "Jane",
              lastname: "Doe",
              age: 42,
            }

            for (const property in someOne) {
              console.log(property, someOne[property])
            }
          

Loops (the ES6 way)


            let iterable = ["A", "random", "assortment", "of", 6, "things"];
            for (const item of iterable) {
              console.log(item)
            }

            iterable = "A random assortment of many more things";
            for (const item of iterable) {
              console.log(item)
            }