๐Ÿ”ฐarrow function as argument

compared with "normal" functions as parameters

JS โŸฉ objects โŸฉ arrow function โŸฉ as argument

  • in the body of an arrow function๏ผšthis is taken from the outside context.

  • in the body of a "normal" function๏ผšthe function has its own this.

๐Ÿ’พ replit๏ผšarrow function as argument

let groupA = {

    title: "Group A",
    students: ["John", "Pete", "Alice"],

    showList() {
        // .forEach()         โ•ญโ”€โ”€ โญ๏ธ arrow function as argument โ”€โ”€โ•ฎ
        this.students.forEach(student =>
            console.log(this.title + ': ' + student)
            //          โ•ฐโ”€โ”€โ•ฏ <---- `this` is taken from the outside โญ๏ธ
        );
    }
};
let groupB = {
    
    title: "Group B",
    students: ["Tom", "Bettie", "Joe"],

    showList() {
        
        // .forEach()         โ•ญโ”€โ”€ โญ๏ธ "normal" function as argument โ”€โ”€โ•ฎ
        this.students.forEach(function(student) {
            //               โ†ฑ โ›” TypeError or `undefined`
            //          โ•ญโ”€โ”€ โญ๏ธ โ”€โ”€โ•ฎ
            console.log(this.title + ': ' + student);
            //          โ•ฐโ”€โ”€โ•ฏ <---- โญ๏ธ "normal" function has its own `this`.
            //                        (which is undefined/window/"global object" by default)
            
            // โญ๏ธ possible errors:
            // ----------------------------------------------------------------------------
            //   `this`       `this.title`            error
            // ----------------------------------------------------------------------------
            // undefined       โŒ             โ›” TypeError: Cannot read property 'title' of undefined
            // window          undefined      no error
            // globalObject    undefined      no error
            // ----------------------------------------------------------------------------
        });
    }
};
  • results๏ผš

groupA.showList();    // this = groupA
// Group A: John
// Group A: Pete
// Group A: Alice

groupB.showList();    // this = globalObject (in Node's environment โญ๏ธ)
// undefined: Tom
// undefined: Bettie
// undefined: Joe

Last updated