Skip to content

Commit 005116e

Browse files
committed
Docs: clarify when traditional functions are preferred
1 parent 0e2ef17 commit 005116e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -949,6 +949,45 @@ Other Style Guides
949949

950950
> Why not? If you have a fairly complicated function, you might move that logic out into its own named function expression.
951951

952+
> **Note:** While arrow functions are recommended for anonymous callbacks, traditional
953+
> function declarations or expressions are still preferred in certain scenarios where
954+
> their behavior is more appropriate.
955+
>
956+
> **Prefer traditional functions when:**
957+
>
958+
> - You rely on **function hoisting**, such as calling a function before its definition.
959+
> - You need a **dynamic `this` binding**, for example in object methods or DOM event handlers.
960+
> - You require access to the **`arguments` object**, which is not available in arrow functions.
961+
>
962+
> **Examples:**
963+
>
964+
> ```js
965+
> // Function hoisting
966+
> initialize();
967+
>
968+
> function initialize() {
969+
> // setup logic
970+
> }
971+
> ```
972+
>
973+
> ```js
974+
> // Dynamic `this` binding (e.g. event handlers)
975+
> const button = document.querySelector('button');
976+
>
977+
> button.addEventListener('click', function () {
978+
> this.classList.add('active');
979+
> });
980+
> ```
981+
>
982+
> ```js
983+
> // Using the `arguments` object
984+
> function sum() {
985+
> return Array.from(arguments).reduce((total, value) => total + value, 0);
986+
> }
987+
> ```
988+
989+
990+
952991
```javascript
953992
// bad
954993
[1, 2, 3].map(function (x) {

0 commit comments

Comments
 (0)