‘Scope’ & ‘Closure’ in JavaScript
There are mainly 3 types of scopes in JavaScript: Global Scope, Function Scope, and Block Scope.
- 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
- 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.
