# Closures

## Rules of closures

1. A closure grants access to the variables passed to a function after it has completed and returned.
2. Helps keep variables from getting pushed into global scope.
3. Provides a degree of protection. Variable can't be overwritten

## File Location

We will be working in the following file:

```
    javascript-library
        └── 1-Fundamentals
            └── 4-Functions
                07-closures.js <----You will be working in this file.
```

## Global Variables

Note below that the function is returning another function:

```javascript
function addSquares(a, b) {
    function square(x) {
        return x * x;
    }
    return square(a) + square(b);
}
var a = addSquares(2, 3); // returns 13
var b = addSquares(3, 4); // returns 25
var c = addSquares(4, 5); // returns 41
```

Take some time to analyze the functions above. Notice that the addSquares function returns the result of the `square` function added together.\
Also, the `square` function is declared inside the scope of the `addSquares` function. Couple more things to note:

1. The square function has access to the addSquares parameters.
2. `square` can't be called outside the scope of `addSquares`&#x20;

## More sample code

Here the inner function has access to outer's variables & parameters

```javascript
function printName(first, last){
    var intro = "My name is ";

    function makeFull(){
        return intro + first + " " + last;
    }
    return makeFull();
}

var d = printName("Paul", "O'Connor");
console.log(d);
```

Couple things to notice:

1. The `intro` variable is used inside of the `makeFull` function.
2. `printName` returns a function `makeFull`.
3. `makeFull` is not accessible outside of the `printName` function.&#x20;

These concepts are the basic building blocks of closures.

## A Challenge

Here's a good challenge to try.

1. Create a function expression called `calculateTotalWithTip`.
2. The function will have two parameters: totalWithoutTip & tipPercentage.
3. Create a totalWithTip variable within the scope of #1.
4. Create a function declaration called `calculateTip` in the scope of #1.
5. The function takes in the same two parameters: totalWithoutTip & tipPercentage.
6. Create a variable in the `calculateTip` function called `tipAmount`.&#x20;
7. `tipAmount` will hold the product of totalWithoutTip & tipPercentage.
8. The `calculateTip` inner function returns `tipAmount`.
9. Set the `totalWithTip` variable equal to the result of running `calculateTip` added to totalWithoutTip.&#x20;
10. Return the `totalWithTip` variable.&#x20;

You can see the answer [here](closures-challenge).
