Marcus Osterberg
2 min readApr 26, 2016

Closures are awesome and confusing

I want to share how I started to understand Closures in JavaScript. This is a beginner friendly view with a simple example. Closures is a function wrapped inside of a functions body that can be referenced to its scope chain e.g. outer variables.

Definition from the book Speaking JavaScript “A closure is a function plus the connection to the scope in which the function was created”- Dr. Axel Rauschmayer

This is how it can look like:

function newCounter() {
let counter = 0
return function increment() {
counter++
console.log(counter)
}
}
let counter1 = newCounter()
let counter2 = newCounter()
// Numbers of events
counter1() // 1
counter1() // 2
counter2() // 1
counter1() // 3

newCounter closes over increment, counter can be referenced to and accessed by increment. If JavaScript would not have closures, we would now have to pass counter to our function increment to be able to access the variable. The closure now holds the scope chain and prevents it from being garbage collected.

counter1 and counter2 will keep track of their own value.

Closures allows us to do function currying. We can create a sequence of functions where each functions takes an individual parameter. For example:

// Lets say we want to create an element with some text and append it to the DOMconst manipulateDOM = (text) => (node) => (appendTo) => {
const newText = document.createTextNode(text)
const newNode = document.createElement(node)
const element = document.querySelector(appendTo)
element.appendChild(newNode)
newNode.appendChild(newText)
}
manipulateDOM('Closure')('div')('#some-id')

All the chained functions above has a closure of the parameters.

I hope this was a clear introduction to what closures are and how they can be used in JavaScript.

Enjoy your code

Marcus Osterberg

Swedish. I like to code, learn new things and travel new places.