Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Javascript Closures

Javascript Closures

Thoughtbot: WWJ Lightning Talk

Meredith Edwards

July 08, 2016
Tweet

More Decks by Meredith Edwards

Other Decks in Education

Transcript

  1. What is a closure? A closure is a function with

    free variables + a referencing environment that closes those variables.
  2. Free variables function counter() { count = count + 1;

    return count; } Free variables are any variables that don’t get defined inside a function. Like here, count is a free variable. It’s not defined inside the counter function. So where is count defined?
  3. count is defined… function makeCounter() { var count = 0;

    function counter() { count = count + 1; return count; } return counter; }
  4. What is a referencing environment? function makeCounter() { var count

    = 0; function counter() { count = count + 1; return count; } return counter; }
  5. Let’s do some work together! Either on your laptop or

    with a neighbor, visit https: //repl.it/languages 1. Under the ‘Popular’ tab, click on JavaScript 2. On the left (white) side of your screen, type: console. log(‘Hello, Jelly!’); 3. Click run 4. Verify that your code is working by looking at the right (black) side of your screen
  6. Copy the code on the left in your JavaScript repl.it

    function makeCounter() { var count = 0; function counter() { count = count + 1; return count; } return counter; } doCount = makeCounter(); console.log(doCount()); console.log(doCount()); console.log(doCount());
  7. What is the closure here? function makeCounter() { var count

    = 0; function counter() { count = count + 1; return count; } return counter; }
  8. Step 2, Illustrated Calling doCount() invokes the counter function function

    counter() { count = count + 1; return count; } var count = 1;
  9. What happens when we call doCount( ) a second time…

    ? function counter() { count = count + 1; return count; } var count = 1;
  10. Calling doCount( ) invokes counter, which increments the count variable:

    counter( ) function counter() { count = count + 1; return count; } var count = 2;
  11. Let’s Review ❏ Wait, what is a closure again? ❏

    I still have a burning question…
  12. Take a look at another example 1. Comment out the

    code in your current repl. 2. Copy the code on the right at the top of your repl. function multiplier(x) { function multiply(y) { return x * y; } return multiply; }
  13. We define ‘y’ by invoking the function with 3: function

    multiply(y) { return x * y; } 3 5 3 multiplyBy5(3) = var x = 5; var y = 3; multiplyBy5(3) => 15
  14. Meredith Edwards Please get in touch! I’d love to hear

    from you. email: [email protected] twitter: @meredith_marg blog: medwardstechblog.wordpress.com