Better Programming

Advice for programmers.

Follow publication

Member-only story

10 JavaScript Closure Challenges Explained With Diagrams

Shuai Li
Better Programming
Published in
6 min readJun 21, 2022

Closures are one of the core concepts in functional programming, and it is must-have knowledge for every JavaScript developer. Here I have prepared 10 closure challenges, many of which are frequently asked in interviews.

Are you ready, challenger? Enjoy this journey!

Each challenge is a code snippet, and you need to say what the output of this code will be.

1. Scope

Before talking about closures, we must understand the concept of scope, which is the cornerstone of understanding closures.

What is the output of this code snippet?

It is very simple. I believe that all challengers know that the output result is 10.

  • By default, there is a global scope.
  • A local scope is created by a function or a code block.

When console.log(a) is executed, the JavaScript engine will first look for a in the local scope created by the function foo. When the JavaScript engine can’t find a, it will try to find a in its outer scope, which is the global scope. Then it turns out that the value of a is 10.

2. Local Scopes

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Shuai Li
Shuai Li

Written by Shuai Li

An enthusiastic game player of Earth Online.

Responses (3)

Write a response