---
# System prepended metadata

title: JavaScript - Closures
tags: [JavaScript, Closures]

---

# JavaScript - Closures

###### tags: `JavaScript` `Closures`

# [Closures - Part 5 of Functional Programming in JavaScript](https://www.youtube.com/watch?v=CQqwU2Ixu-U)

function are also closures


function body has access to variables that are defined out function
we are not passing in an argument 
we're just calling it without any arguments
we are directly referring to the ``me`` that is assigned outside of the function scope
not copy, rather a reference
function is called from a completely different part of application 
or a different module
it will still refer to this specific context

## Why closure is useful

when you start a task and you want to spedify something that happens
when that task is done with stuff that is available to you when you start the task 
closures


class, this reference cannot be referenced by outside

---

# [Closures / MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)


## Lexical Scoping

Consider the following example code:
```
function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
  }
  displayName();
}
init();
```

``init()`` creates a local variable called ``name`` and 
a function called ``displayName()``. 
The ``displayName()`` function is an __inner function__ 
that is defined inside ``init()`` and 
__is available only within the body__ of the ``init()`` function. 
Note that the ``displayName()`` function __has no local variables of its own__. 
However, since inner functions __have access to the variables of outer functions__, 
``displayName()`` can access the variable ``name``
 declared in the parent function, ``init()``.

Run the code using this JSFiddle link and notice that 
the ``alert()`` statement within the ``displayName()`` function 
successfully displays the value of the ``name`` variable, 
which is declared in its parent function. 
This is an example of lexical scoping, 
which describes how a parser resolves variable names 
when functions are nested. 
The word __lexical__ refers to the fact that 
lexical scoping uses the location where 
a variable is declared within the source code 
to determine where that variable is available. 
__Nested functions have access to variables declared in their outer scope__.


## Closure

Consider the following code example:

```
function makeFunc() {
  var name = 'Mozilla';
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();
```

Running this code has exactly the same effect 
as the previous example of the ``init()`` function above. 
What's different (and interesting) is that 
the ``displayName() ``inner function 
__is returned from the outer function before being executed__.

At first glance, it might seem unintuitive that this code still works. 
__In some programming languages, 
the local variables within a function exist 
for just the duration of that function's execution__. 
Once ``makeFunc()`` finishes executing, 
you might expect that __the ``name`` variable would no longer be accessible__. 
However, because the code still works as expected, 
this is obviously not the case in JavaScript.

The reason is that functions in JavaScript form closures. 
__A closure is the combination of a function and 
the lexical environment within which that function was declared__. 
__This environment consists of any local variables that 
were in-scope at the time the closure was created__. 
In this case, ``myFunc`` is a reference to 
the instance of the function ``displayName`` created 
when ``makeFunc`` is run. The instance of ``displayName`` 
__maintains a reference to its lexical environment__, 
within which the variable ``name`` exists. 
For this reason, when ``myFunc`` is invoked, 
the variable name remains available for use, 
and "Mozilla" is passed to alert.

Here's a slightly more interesting example—a ``makeAdder`` function:
```
function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

```

In this example, we have defined a function ``makeAdder(x)``, 
that takes a single argument ``x``, and 
returns a new function. 
The function it returns takes a single argument ``y``, 
and returns the sum of ``x`` and ``y``.

In essence, ``makeAdder`` is a __function factory__. 
It creates functions that can __add a specific value to their argument__. 
In the above example, the function factory 
creates two new functions—
one that __adds five__ to its argument, 
and one that __adds 10__.

``add5`` and ``add10`` __are both closures__. 
They __share the same function body definition, 
but store different lexical environments__. 
In add5's lexical environment, ``x`` is 5, 
while in the lexical environment for ``add10``, ``x`` is 10.

closure 的一種use case - factory function

``add5`` and ``add10`` 從程式碼看起來只是變數,
但實際上是由 factory function ``makeAdder``
建立出的2個 closures 共享程式碼 ``makeAdder``
但在 Runtime 下, 有各自個lexical environments
``add5`` 的 ``x=5``
``add10``  的 ``x=10``

神奇是可以引用 closure 
因為它內部會 return 另一個 function 計算的結果
--> 引用它等於是引用它內部的 function 並 return 計算結果

---

# [Understanding JavaScript Closures](https://medium.com/codex/understanding-javascript-closures-5b3f184e82ec)

Today I am going to talk about a very confusing 
but fundamental topic in JavaScript programming. 
I had a hard time wrapping my head around JavaScript closures. 
After a very painful interview question on this topic 
I decided to really try and understand closures and 
why they can be useful. 
I will also do my best to explain it in a clear way. 
Let’s get started.

So what is a closure? 
A closure is __a function bundled with references to its surrounding state__. 
In clearer terms we could say that 
__a closure is a function inside an outer function 
that has access to the outer function’s scope__. 
The closure has access to its own variables, 
the outer function’s variables and the global variables. 
Just reading this might not make much sense so let’s look at an example.

closure 是 outer function 內部中的 function
它能存取自己 scope 中的 variables, 
也能存取 outer function scope 中的東西 (variables),
當然能存取 global variables

```
function outer() {
	let a = 10;

	function inner() {
		let b = 10;
		console.log(a + b);
	}
	return inner;
}

myFunc = outer();
myFunc()	// Console Logs: 20
```

We have two functions here. The outer function has a variable named ‘a’ and returns the inner function. The inner function has a variable named ‘b’ and accesses the variable from the outer function. After that we save the results of the execution of the outer function into a variable ‘myFunc’. That means that ‘myFunc’ is now holding the inner function. When executed we actually get the sum output on the terminal. Why? At first it might not make sense that this code actually works. In other programming languages, the local variables within a function exist for just the duration of that function’s execution. You might expect that after the outer function executes the ‘a’ variable would no longer be accessible. This is not the case in JavaScript thanks to closures. A closure is the combination of a function and the lexical environment where the function was declared. This environment consists of any local variables that were in-scope at the time the closure was created. This feature of JavaScript allows code like this to run. Things get a lot more interesting when these functions start taking arguments. Let’s take a look at an example.


```
function adder(x) {
	function inner(y) {
		return x + y;
	};
	return inner
}

let add10 = adder(10);
let add20 = adder(20);

console.log(add10(10));	// 20
console.log(add20(5));	// 5
```

Closures let you associate data with a function that operates on that data. This can be compared to how in object-oriented programming objects allow you to associate data with methods. As you can see we can save the closure into two different variables and the operation on different values. Even though the outer function already ran the environment within it is still accessible to the inner function because it was saved in memory. The environment is stored by the closure for its own later use.

I hope this will help anyone out there understand the basics of closures. It is a very interesting topic and there is still many more things I need to learn about it. Practicing with them will only help more. Questions about closures are frequently asked during interviews so it is very important to understand this concept in order to ace the interview. Happy coding! 

