Learn in Public
  • Initial page
  • NOTES
    • Data Structures
      • Use cases
    • System Design
    • Angel Investing
    • Blockchain
      • Blockchain Interoperability
      • Consensus Algorithm
      • Wallet
      • dApps
    • Brain-computer interface
    • Cognitive Science
      • Memory
      • Neuroeconomics
    • JavaScript
      • Date
      • 📚Untitled
      • Basics
      • Front-end Interview Questions
      • JS Snippets
    • Machine Learning
      • OpenAI
    • MongoDB
    • GraphQL
    • TypeScript
    • UI / UX
    • Design Systems
    • Web Development
      • React
        • File Structure
        • Hooks 🎣
        • Next.js
      • Fetch API
      • Deployment
      • Accessibility
      • DNS Settings
      • css
        • CSS Structure
      • Pretty Website
      • Design Tools
      • Snippets
    • Remote
    • Flight Pricing
    • Mental Model
    • Surveillance
    • Web optimization
    • Archive
      • Cannabis
Powered by GitBook
On this page

Was this helpful?

  1. NOTES
  2. JavaScript

Basics

PreviousUntitledNextFront-end Interview Questions

Last updated 6 years ago

Was this helpful?

Closures

A closure is the combination of a function and lexical environment which that function was declared. It executes with the scope that was defined in place, not with the state that's in place when it is executed. A function with lexical scope is able to access variables that were defined in the parent scope.

const prepareBark = dog => {
  const say = `${dog} barked!`
  return () => {
    console.log(say)
  }
}

const rogerBark = prepareBark(`Roger`)
const sydBark = prepareBark(`Syd`)

rogerBark() // Roger barked!
sydBark() // Syd barked

When we redefine a new say variable, it doesn't change the state of the first scope of prepareBark()

Why would you use one?

  • Data privacy / emulating private methods with closures. Commonly used in the .

  • .

References

module pattern
Partial applications or currying
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures