Looking for Closure? (Javascript)

Photo by Cristina Gottardi on Unsplash

So what are the Closures in Javascript?

Closures in Javascript are nothing but functions with preserved data. A closure is a function that has access to variables defined in an outer function that have previously returned.

>> outer()> () => {
let innerData = " and this is inner"
return outerData + innerData
}
>> outer()()> "This is outer and this is inner"
> k = outer(4)
> console.dir(k)
Notice that Closure Scope has x value as 4
>> let letsCount = counter()
>> letsCount()
> 1
>> letsCount()
> 2
>> letsCount()
> 3
>> count
> Uncaught ReferenceError: count is not defined(...)
>> let week1 = shoppingList()
>> let week2 = shoppingList()
>> week1.getList()
> ["Milk","Bread","Eggs"]
>> week1.addToList("Onions")
> ["Milk,"Bread","Eggs","Onions"]
>> week2.getList()
> ["Milk","Bread","Eggs"]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ali Erbay

Ali Erbay

7 Followers

Full Stack Developer BDD/TDD || Ruby on Rails || React || React Native || NodeJS || Express https://github.com/kermit-klein