DEV Community

Discussion on: Seriously though, what is Closure?!

Collapse
 
indoor_keith profile image
Keith Charles • Edited

Your explanations are well put. Great read! Quick note on formatting. if you place a "js" right after the first set of backticks, DEV will highlight your syntax accordingly 🙂. So it would look like so if you replaced the single quotes with backticks:

'''js
// your code here
'''

Lastly, whereas your last example showcases the idea of closures, it doesn't quite reflect the benefit of them. A great example of a closure utilizing a lexically scoped variable would be a persistent counter without a global count variable. We know that whenever a function runs, it rebuilds any variable that is declared inside of it, rendering those variables non-persistent if we need to call that function multiple times. And if we don't want to pollute our global scope, we wouldn't want to declare the variable outside of any function. We'd need a closure to handle counting said variable! Example:

// a function that creates the count variable and the closure 
// that will increment said variable
function createCounter() {
  // our block scoped variable
  let count = 0;
  // our closure
  function increment() {
    count++;
    return count;
  }
  // we return our closure to be used outside of createCounter
  return increment;
}

// now we can store the result of createCounter to use our 
// closure as many times as we want without the need to expose
// our count variable globally to access and increment it.
const getIncrement = createCounter();

console.log(getIncrement()); //-> 1
console.log(getIncrement()); //-> 2
console.log(getIncrement()); //-> 3
Enter fullscreen mode Exit fullscreen mode

When you think of closure's this way, you begin to see how powerful closures are. You're essentially creating a manageable state without the need to expose any variables globally! 🤯

I'm excited to read more of your posts and welcome to the Dev Community! ✌