Function Scope, Block Scope and Lexical Scope (JavaScript).

Through this article I will explain three basic concepts that every Javascript developer should know.

Note: This article was based on this git-hub repository, so all credits to their respective owners.

1.- Context:

It refers to the value of “this” when an object is created. Let’s look at some examples to explain the concept more clearly.

2.- Scope:

It refers to where a variable can be accessed in a program. In some cases a variable can be accessed from anywhere (global scope), while others have more restricted context ( function scope or block scope). Let’s dive into all scope types exist, and how they works.

2.1 Global Scope:

If a variable or function is not defined within a block or function, we can say that variable or function belongs to global scope, and it can be accessed from anywhere in a program.

2.2 Local Scope:

Variables are defined within a block or a function, and they can only be accessed where they were defined. Here there are two types of local scope, Block Scope and Function Scope.

Function Scope:

  • variables defined inside the function and are accessible within the entire function.
  • the type “var” always has function scope.

Block Scope:

  • variables are defined within curly braces “{}” , those variables will be accessed inside the block where they were defined.
  • types “let” and “const” will always have block scope

3.3 Lexical Scope:

Is the ability for a function scope to access variables placed in a parent scope. In other words, a child function is lexically bound to its parent function.


Finally, I want to share with you this table that shows the differences among the three data types that there are in JavaScript and how they work according to the scope they are.

Backend Developer