DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 10: Scope

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"
Enter fullscreen mode Exit fullscreen mode

Local & global scope visualisation

Image description

Expanded local scope

Image description

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.

Image description

Question for you

Why local scope is not showing here?.

Image description

Write the answer the comments.

Top comments (5)

Collapse
 
overflow profile image
overFlow

could it be becaiuse const my Closure is declared outside scope of any function?

Collapse
 
dhrn profile image
Dharan Ganesan • Edited

myclosure code is executing the global scope, so local scope is global.

Collapse
 
overflow profile image
overFlow

very confusing stuff. i still d not grasp it.

Thread Thread
 
dhrn profile image
Dharan Ganesan

when you execute the code in default scope, by default you are in global scope, i.e local scope = global scope = window.

Image description

Thread Thread
 
overflow profile image
overFlow

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.