JavaScript Scopes And Closures

By | 21 July, 2016
Share Article

In this post we will learn about JavaScript Scopes And Closures. In JavaScript functions and objects are also variables. A scope is a term which is used to define a region in source code. In this region a variable can be defined and accessed without any errors. In JavaScript scope is a Lexical Scope or Static Scope.

JavaScript has two types of scopes

  • 1) Global Scope: Once an variable defined in Global scope than can be accessed and modified anywhere even within different program files. For example

    or you can assign the value to this variable in the below way too
  • Local Scope : A variable declared inside a function can be accessed within the function. So, scope of that variable is limited to function and this variable cannot be accessed by any other code outside the function. So, the variable is known as local variable and scope of that function is LocalScope. Local variable is created and destroyed each time when function is executed.

Closures are functions that refer to variables that are used locally, but defined in an enclosing scope (Independent (free) variables).
In simple words, these functions ‘remember’ the environment in which they were created.

In JavaScript each function have access to globas scope. As well as each function have access to scope above them (Parent Scope). JavaScript allow to use nested functions. So, the nested function have access to the scope of function in which they defined.

 

Leave a Reply

Your email address will not be published. Required fields are marked *


*