JSFiddle - React, Tailwind, and code Playground

by Ramya Ranganathan

JavaScript

/* Closure Question
I just saw a posted question about closures that made me realize I still don't understand the concept.
 
Does the example involving moving the puck from week 9 (lesson 3) show a closure since the method movePuck() is declared inside another function and has access to variables inside that containing function? Why or why not?
 
The idea of a function being kept alive after a function has returned is also confusing me....
 
Thanks! */


    // this is essentially window.counter
var counter = 0;

// counter is now 1
counter+=1;
// counter is now 2
counter+=1;

// alternatively you can create a function that accesses the global variable
function increaseCounter() { counter+=1; }

// counter is now 3
increaseCounter(); //this is doing it as a global variable


//Well, what if we wanted the variable "counter" to not be global? Let's try making it a private variable inside increaseCounter()

var increaseCounter = function() {
    var counter = 0;
    counter += 1;
    return counter;
}
//We've accomplished making our "counter" variable private. The only issue here is that every time we call increaseCounter(), the variable "counter" is reset back to 0. So, is there a way to avoid this?
//Well, what if we used an inner function to increase "counter" and let the outer function just run once?
// the outside function just runs once, enough for us to create the variable "counter"
// and the inner function increaseCounter()
var createCounter = function() {
    var counter = 0;

    function increaseCounter() {
        counter += 1;
        return counter;
    }
}
/*Great right? Only problem is that increaseCounter is also a private variable and there is no way for us to access it.
So how about this. Let's make the run-once function createCounter() reference increaseCounter() after it has executed. That is, we want createCounter to do the following:
1) Create a private variable called "counter".
2) Create a private function called "increaseCounter".
3)...