Day 10: Scope

Dharan Ganesan - Jul 21 '23 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player