‘Scope’ & ‘Closure’ in JavaScript

Jake jonggu baek
2 min readJan 16, 2024

There are mainly 3 types of scopes in JavaScript: Global Scope, Function Scope, and Block Scope.

  1. Global Scope : Variables declared outside of any function or block have global scope and they can be accessed from anywhere in the script.

2. Function Scope: Variables declared inside of a function have function scope, which make them be only accessible from the function.

3. Block Scope: Variables declared within a specific block(a set of statements enclosed within curly braces ‘{}’) of code. The introduction of ‘let’ and ‘const’ in ES6 brought block-scoping to JavaScript

Closure is a feature that allows a function to remember and access variables from the outside of its scope. This means that a function closes over its lexical scope, capturing the variables in the scope and allowing them to be referenced later.

I will show you two examples of closure

  1. Closure in a loop: Since the loop has already completed when the functions are invoked, the variable has already the final value of 5 therefore each function outputs 5 when they are executed.

2. Closure with asynchronous code: The Inner function(getResult) can capture the outer scope’s variables(result) even after the outer function has completed.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Jake jonggu baek
Jake jonggu baek

No responses yet

Write a response