Roxy Palma
Roxy Palma

Reputation: 33

Can a callback function be a closure?

getTotal() {
    let total = 0;
    this.results.forEach(result => {
        total += result.marks;
    })
    return total;
}

Is call back function inside forEach method be a closure as it is accessing the total variable outside its scope?

Upvotes: 0

Views: 85

Answers (2)

CoderDesu
CoderDesu

Reputation: 895

Yes, this is closure. Your anonymous cb function has been declared in the same scope as a total variable and anonymous cb got an implicit[[Environment]] property, where your total variable is stored. Check it here. https://javascript.info/closure

Upvotes: 0

artem
artem

Reputation: 457

yes, it's. Use reduce for folding:

 return this.results.reduce((total, result) => total + result.marks)

Upvotes: 1

Related Questions