You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit f6ae327
Browse filesBrowse the repository at this point in the historyBrowse files
The `greetPerson` function (the "outer" function) contains another function inside its function body, called `innerFunction`. This inner function has access to the `name` argument of `greetPerson`, as well as its own `greeting` argument.
18
+
## Description
19
19
20
-
When we later call `greetPerson('Timir')`, the `greetPerson` function sets its `name` argument to the string `'Timir'` and returns its inner function. This inner function **retains access to the `name` argument** and its value `'Timir'`, even after `greetPerson` exits. (Note that `greetPerson` doesn't call its inner function; it just returns it.)
20
+
The `greetPerson` function (the "outer" function) contains an enclosed function, named `innerFunction`. This inner function has access to the `name` argument of its enclosing function `greetPerson`, as well as to its own `greeting` argument.
21
21
22
-
The returned the inner function is subsequently assigned to the variable `greetTimir`.
22
+
When we later call `greetPerson` passing `'Timir'` as its parameter, the `greetPerson` function sets its `name` argument to `'Timir'` and returns its inner function. This inner function **retains access to the `name` argument** and its value `'Timir'`, even after `greetPerson` exits. (Note that `greetPerson` doesn't call its inner function; it just returns it.)
23
+
24
+
The returned inner function is subsequently assigned to the variable `greetTimir`.
23
25
24
26
> A closure is an inner function that has access to the outer (enclosing) function’s variables and arguments.
25
27
26
-
With `greetTimir('Good morning')` we are effectively calling the inner function, passing it the string `'Good morning'`. Because the inner function still has acces to `name` it can produce the output as printed by the `console.log`:
28
+
With `greetTimir('Good morning')` we are effectively calling the inner function and passing it the string `'Good morning'`. Because the inner function still has access to `name` it can produce the output as printed by the `console.log`:
27
29
28
30
```
29
31
Good morning, Timir
30
32
```
31
33
34
+
## Alternative implementation
35
+
32
36
We could have obtained the same result by scrapping all lines except the last two and replace them with an equivalent, custom made `greetTimir` function as shown below. We wouldn't be able to tell the difference from just looking at the output produced.
33
37
34
38
```js
@@ -53,7 +57,7 @@ const hasanGreeting = greetHasan('Have a good day');
0 commit comments