phuocng / this-vs-that

Understanding the difference between ˍˍˍ and ˍˍˍ in front-end development
https://phuoc.ng/collection/this-vs-that
MIT License
1.47k stars 98 forks source link

[JS] Anonymous vs closure functions #283

Closed phuocng closed 1 year ago

MkDev11 commented 1 year ago

Anonymous functions and closure functions are both concepts in JavaScript related to the way functions are defined and how they capture and interact with variables in their surrounding scope. Let's explore each of these concepts:

Anonymous Functions:

Closure Functions:

Key Differences:

  1. Naming: Anonymous functions have no names or identifiers, while closure functions have names.

  2. Scope: Both types of functions can capture and access variables from their outer scope. However, closure functions are specifically known for their ability to create closures, which allows them to retain access to those variables even after the outer function has completed execution.

  3. Use Cases: Anonymous functions are typically used for short-lived, one-off tasks like callbacks. Closure functions are used to create self-contained and stateful modules or to capture and maintain state across multiple function calls.

In summary, anonymous functions are a common and convenient way to define functions without naming them, often used in callback scenarios. Closure functions, on the other hand, are functions that capture and preserve access to variables from their surrounding scope, making them a powerful tool for encapsulating state and behavior. While they are different concepts, a closure function can also be an anonymous function if it's defined without a name.

phuocng commented 1 year ago

Done: https://phuoc.ng/collection/this-vs-that/anonymous-vs-closure-functions/