JS-101-Fundamentals
  • JavaScript Library
  • 1-JavaScript Fundamentals
    • 0-Getting Started
      • Welcome
    • 1-JS-Fundamentals
      • 1-Grammar and Types
        • Comments
        • Declarations
        • Scope
        • Hoisting
        • Types
        • Literals
      • 2-Control Flow and Error Handling
        • if
        • if else
        • switch
        • try catch
        • throw
      • 3-Loops
        • For Loops
        • For In Loops
        • For Of Loops
        • Do While
        • While Loops
      • 4-Functions
        • Declarations
        • Expressions
        • Calling Functions
        • Scope
        • Parameters
        • Arguments
        • Closures
        • Closures Challenge
        • Arrow Functions
        • Predefined
      • 5-Expressions and Operators
        • Assignment
        • Comparison
        • Ternary
        • Typeof
        • Left Hand Side
        • Spread
      • 6 Numbers and Dates
        • Numbers
          • Numbers Enhanced
        • Math
        • Dates
      • 7 String Methods
        • String Literals
        • Methods
      • 8 Regular Expressions
        • Basic Intro
      • 9 Arrays
        • Array Review
        • Populating/Referring
        • Length
        • Iterating
        • Methods
      • 10 Objects
        • About Objects
        • Properties
        • Enumeration
        • Initializers
        • Constructor Functions
        • this
        • create
        • Methods
      • 11 ES6 Intro
        • ES6 Intro
        • let
        • const
Powered by GitBook
On this page
  • Rules of closures
  • File Location
  • Global Variables
  • More sample code
  • A Challenge
  1. 1-JavaScript Fundamentals
  2. 1-JS-Fundamentals
  3. 4-Functions

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:

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

More sample code

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

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.

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.

  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.

  10. Return the totalWithTip variable.

PreviousArgumentsNextClosures Challenge

Last updated 7 years ago

You can see the answer .

here