The Difference Between Function, Block, and Lexical Scope
August 6th 2021
ยท 5 min read
The concept of variable scope might confuse some of us, but it is an essential concept that every developer must fully understand. So, this article will include a brief explanation of this concept and will list 3 different types of scope in javascript, and it will include a video explaining this topic.
What is variable scope?
Variable scope is the location where a variable is defined and the context where other pieces of your code can access and manipulate it. In other words, the variable scope defines where your variables can be obtained to work with it either to be displayed or do arithmetic operations on it. Function, block, and lexical scopes are going to be discussed throughout this article.
Function Scope
Function scope is where the variable is visible only within a function, and it cannot be accessed outside the curly brackets of the function. In javascript, var is the keyword that is used to declare a variable for a function scope accessibility.
Block Scope
Block Scope is the area within if, switch conditions and for, while loops. In ES6, const and let are the keywords that are used to define variables for a block scope accessibility, which means that those variables exist only within the corresponding block.
Lexical Scope
Lexical scope means that the childrens' scope has access to the variables declared in the parent scope, so if we have 2 nested functions, the inner function can access the variable declared in the outer function using any of the keywords used in javascript either with var, let or const. This means that the children's functions are lexically bound to their parents.
As we mentioned above, the variable scope is an important concept that every programmer should grasp. Hopefully, this article can help you achieve that. The attached video below explains this topic in greater detail and provides examples for these types of variable scopes.
Be the first to comment on this article
In order to comment, please enter your information below.
Thank you for commenting!
Your comment will be visible shortly.