Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lexical Scope in JavaScript

I am slightly confused as to how exactly scope works in JavaScript, mainly lexical scope. I understand that variables in global scope are accessible anywhere, and the only way to create a new scope in JavaScript is through the creation of functions (or with let in ES6). However, I do not really understand what lexical scope is/means. I have looked all over the internet and could not find a clear explanation.

I feel like I am kind of starting to understand it, but just let me confirm with you JavaScript wizards out there to make sure that I am correct.

So, from my understanding, lexical scope means statically scoped, so for example, a function's scope is not created by where it is called but by where the function itself is created. The following code below demonstrates this concept:

var x = "global";

function foo() {
   console.log(x);
}

function bar() {
   var x = "bar";
   foo();
}

function baz() {
   var x = "baz";
   foo();
}


bar();
baz();

What is printed to the console is "global" twice. This is because when the function foo is invoked, the interpreter first checks foo's scope to see if it has a variable "x" then checks the global scope, not bar or baz scope. The variable "x" is grabbed, not from where the function foo is called, but from where it is created, hence lexically scoped. Am I correct, and is this making sense?

Another example of lexical scope would be closures, right? So for example, the inner function has access to the outer function's variables, no matter where the inner function is called because of lexical scope, correct?

Finally, my last example would be arrow functions. They allow for the lexical scoping of "this", right? So, for example,

   var obj = {
       name: "Rob",
       print() {
       setTimeout(() => {
         console.log(this.name)
       }, 1000);
     }
   };

Rather than "this" being bound to the global object if it were a standard inline function, "this" is bound to obj because of the lexical scoping of "this" with arrow functions.

Is everything I have said correct? Also, can someone just give me a clear-cut definition of lexical scope? Are there any other examples of lexical scope in JavaScript that I should know about?

Thanks.

like image 874
Anonymous Avatar asked Jan 17 '18 06:01

Anonymous


People also ask

What is the difference between lexical scope and closure in JavaScript?

A closure in JavaScript is a feature where an inner function has access to the outer (enclosing) function's variables — a scope chain. Closures in Javascript are created along with the function. Lexical scoping is the environment that holds the variables of the current scope as well as the outer scope.

What is lexical scope in ES6?

While in ES5 'this' referred to the parent of the function, in ES6, arrow functions use lexical scoping — 'this' refers to it's current surrounding scope and no further. Thus the inner function knew to bind to the inner function only, and not to the object's method or the object itself.

What is lexical scope go?

Lexical scoping allows variables to be declared within a specific scope and it is only accessible within that region. Lexical scoping allows for lexical closures, but the absence of closures still ensures that the scope allows the function to be re-entrant.

What is a lexical variable in JS?

A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration. But the opposite is not true; the variables defined inside a function will not be accessible outside that function.


1 Answers

To understand the lexical scope you need to have a basic understanding of the scope. In javascript, we have classified scope in three types

  1. Function scope
  2. Block Scope
  3. Lexical Scope

Function Scope -> The variables defined inside the function are considered in function scope.the var keyword is used to define the variable in the function scope.

Block scope -> The variables defined in the area within if,switch condition,for,and while loops. whenever you see '{}' curly braces, its a block. In Es6 const and let keywords allow developers to declare a variable in the block scope. which means those variables exist only within the corresponding block.

   function animal(){
    if(true){
        var animal1 = "cat";
        const animal2 = "dog";
        let animal3 = "rat";
    }
    console.log(animal1);
    console,log(animal2); //animal2 is not defiend
    console,log(animal3); //animal3 is not defiend
}
animal();

result

cat

animal2 is not defined

animal3 is not defined

Lexical scope-> In 1 line I want to say "children scope have access to the variable in parent scope" `

var outerFunction = function()
{
    if(true){
        var x = 5;
        const y = 10;
    }

    var innerFunction = function(){
        if(true){
            alert(x);
            //alert(y);   //y is not defiend on line 13

        }
    }
    innerFunction();
}
 outerFunction();
 //console.log(x); // x is not defiend on line 20

`. The scope of a variable is defined by their position in the source code. In order to resolve variable javascript starts at the innermost scope and searches outward until it finds the variable it was looking for. lexical scoping is nice because we can easily figure out what the value of a variable will be by looking at the code; whereas in dynamic scoping the meaning of a variable can change at runtime by making it more difficult

like image 61
Ujjwal Rajpal Avatar answered Sep 30 '22 12:09

Ujjwal Rajpal