DEV Community

Dan Bui
Dan Bui

Posted on

Lexical scope in JavaScript

Recently, a friend asked me, “What is lexical scope? Is it a type of Scope?”:). Great question!. Scope in JS often causes confusion. In this post, let’s discover Scope, Lexical scope in JavaScript

Scope

Let’s start with scope. Scope determines the accessibility of variables. There are 3 types of scope:

  • Global
  • Function
  • Block

Global Scope

  • Variables are declared outside any function or block
  • Can be accessed everywhere in the code

Function Scope

  • Variables are declared inside a function
  • Can be accessed only in a function, nested function, and can not be accessed outside of this function

Block Scope

  • Variables are declared inside a block (for, if..) (let, const)
  • Can be accessed only in a block scope, can not be accessed outside of this block
  • var doesn’t have block scope (because of hoisting, it will be moved on top of their scope, outside of block scope)

The question: “Is lexical scope the 4th scope in the above list?”

Lexical scope
Pay your attention to example below:

var babyName = 'globalBaby';

function foo(){
    console.log('babyName', babyName);
}

function bar(){
    var babyName = 'Doraemon';
    foo();
}

bar();

/// What will be logged?
Enter fullscreen mode Exit fullscreen mode
  • Define global babyName
  • Define foo function, try log babyName
  • Define bar function , declare babyName inside this function (function scope)
  • Call bar function

So far, we know about function scope. As the definition, inside bar function the babyName can be accessed by foo function . Let’s check the result of above example

var babyName = 'globalBaby';

function foo(){
    console.log('babyName', babyName);
}

function bar(){
    var babyName = 'Doraemon';
    foo();
}

bar();
/// What will be logged?
/// Actual logging: babyName globalBaby
Enter fullscreen mode Exit fullscreen mode

The value of babyName is ‘globalBaby’, not Doraemon, as we expected? But why? That is the mechanism of scope known as Lexical scope or Static Scope. Lexical scope is a fundamental principle; it determines the accessibility of a variable based on where the code is defined rather than when the code is run. We can think, the lexical scope is similar to the scope’s property.

The value of babyName is ‘globalBaby’ because:

  • Foo function “remember" babyName = ‘globalBaby’ at the define time
  • At the run time, inside bar function Foo function can not access babyName which is defined inside this function

Conclusion

Scope is a crucial fundamental, but developers often miss it. I am one of them 😃 . A solid understanding of scoping helps us code and debug better! If you have any comments or adjustments, feel free to drop a comment

Top comments (0)