Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope Chain in Javascript

I've reading scope chain in Javascript but it didn't make any sense to me, could any one tell me what is scope chain and how it works with a graphic or something even an idiot can understand. I googled it but I didn't find something comprehensible :(

like image 625
Tarik Avatar asked Sep 27 '09 18:09

Tarik


People also ask

What is scope chain and lexical scoping?

It is the process in which, JavaScript engine searches for the value of the variables in the scope of the functions. However, the search is in a lexical manner. First of all the engine looks out in the current scope of the current function. If not found, it finds it in the parent funtion.

What are the three types of scopes in JavaScript?

JavaScript has 3 types of scope: Block scope. Function scope. Global scope.

What are the 3 types of scope?

- [Instructor] In JavaScript there are a few different types of scope, local, global and block scope. We'll explore each one in depth with code examples but, in short, local scope is when a variable object or function is only available locally to a function, like the warrior2 variable.

How the scope works in JavaScript?

In JavaScript, scopes are created by code blocks, functions, modules. While const and let variables are scoped by code blocks, functions or modules, var variables are scoped only by functions or modules. Scopes can be nested. Inside an inner scope you can access the variables of an outer scope.


1 Answers

To understand the scope chain you must know how closures work.

A closure is formed when you nest functions, inner functions can refer to the variables present in their outer enclosing functions even after their parent functions have already executed.

JavaScript resolves identifiers within a particular context by traversing up the scope chain, moving from locally to globally.

Consider this example with three nested functions:

var currentScope = 0; // global scope (function () {   var currentScope = 1, one = 'scope1';   alert(currentScope);   (function () {     var currentScope = 2, two = 'scope2';     alert(currentScope);     (function () {       var currentScope = 3, three = 'scope3';       alert(currentScope);       alert(one + two + three); // climb up the scope chain to get one and two     }());   }()); }()); 

Recommended reads:

  • JavaScript Closures
  • Closures
like image 154
Christian C. Salvadó Avatar answered Sep 18 '22 01:09

Christian C. Salvadó