🔰arrow function as argument

compared with "normal" functions as parameters

JSobjectsarrow function ⟩ as argument

💾 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

Was this helpful?