What is Scope in JavaScript?
Scope refers to the context in which variables and functions are declared and can be accessed. In other words, it defines the portion of code where a particular variable or function is visible and can be referenced. JavaScript has two primary types of scope: global scope and local scope.
Global Scope:
Variables and functions declared outside of any function or block are said to have global scope. They are accessible from any part of your code, both inside functions and outside of them.
Local Scope:
Variables and functions declared inside a function or block have local scope. They are only accessible within that specific function or block and are not visible outside of it.
function outerFunction() {
const message = "Hello";
function innerFunction() {
console.log(message);
}
return innerFunction;
}
const myClosure = outerFunction();
myClosure(); // Output: "Hello"
Local & global scope visualisation
Expanded local scope
Closure
The innerFunction is defined inside the outerFunction, which means innerFunction has access to the variables in the lexical scope of outerFunction.
In this case, the message variable is in the lexical, forming a closure.
Question for you
Why local scope is not showing here?.
Write the answer the comments.
Top comments (5)
could it be becaiuse const my Closure is declared outside scope of any function?
myclosure code is executing the global scope, so local scope is global.
very confusing stuff. i still d not grasp it.
when you execute the code in default scope, by default you are in global scope, i.e local scope = global scope = window.
I appreciate your answers thank you but i still will need to deep dive into this concept. Its either I am not smart enough or I need a different perspective.
My progress is grinding slow these days.