Javascript

Posted by Luna on April 5, 2022

Loops

  1. while
  2. do/while
  3. for
  4. for/of work with iterable objects

    Introduced in ES6.

    For/of with arrays, strings, sets

    1
    2
    3
    4
    
    let data = [1, 2, 3, 4, 5], sum = 0;
    for (let element of data) {
        sum += element
    }
    

    For/of with objects.

    Objects are not by default iterable. Script below will throw an error:

    1
    2
    3
    4
    
    let o = {x : 1, y: 2, z: 3}
    for (let element of o) {
        console.log(element)
    }
    

    However we can use for/of to loop through object.keys(), object.values(), object.entries():

    1
    2
    3
    4
    
    let pairs = "";
    for (let [k, v] of Object.entries(o)) {
        pairs += k + v;
    }
    
  5. for/in

    It has some tricky results. For example:

    a is an array, i will be the index instead of the elements in a as expect.

    1
    2
    3
    
    for (let i in a) {
       console.log(i);
    }
    

Asynchronous