Skip to content

JavaScript Closures explained

New Course Coming Soon:

Get Really Good at Git

A gentle introduction to the topic of closures, key to understanding how JavaScript functions work

If you’ve ever written a function in JavaScript, you already made use of closures.

It’s a key topic to understand, which has implications on the things you can do.

When a function is run, it’s executed with the scope that was in place when it was defined, and not with the state that’s in place when it is executed.

The scope basically is the set of variables which are visible.

A function remembers its Lexical Scope, and it’s able to access variables that were defined in the parent scope.

In short, a function has an entire baggage of variables it can access.

Let me immediately give an example to clarify this.

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


This logs to the console Roger barked!, as expected.

What if you want to return the action instead:

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

const bark = prepareBark(`Roger`)


This snippet also logs to the console Roger barked!.

Let’s make one last example, which reuses prepareBark for two different dogs:

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

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


This prints

Roger barked!
Syd barked!

As you can see, the state of the variable say is linked to the function that’s returned from prepareBark().

Also notice that we redefine a new say variable the second time we call prepareBark(), but that does not affect the state of the first prepareBark() scope.

This is how a closure works: the function that’s returned keeps the original state in its scope.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: