DEV Community

Cover image for Javascript - Scope, Closure
Shuvro_baset
Shuvro_baset

Posted on

Javascript - Scope, Closure

*Scope: *
It’s a very important topic in javascript. It mainly defines where we can use our variables and functions in javascript. When we declare a variable and function and after that we use them. But we did not use them all over the script. There are some restrictions and that is known as scope.

There are two types of scops
Local scope
Global scope

It defines where we can access the variables and functions
Every new functions creates a scope
A variable that is declared in a function and that function can not be used in other functions.

1. Local Scope:
We declare variables in a function called local variables. These variables are local scope. It means we can use these variables only under that function. We did not use any outer function. In that case you will get an error.

*2. Global Scope: *
Global scope means that access is everywhere. We declare variables not in any function that are known as global variables. These variables are global scope. We can use these variables anywhere in the script.

Lexical Scoping:
Every child function can access their parent functions. We declare a function and under that function we declare a variable x and another function y(). So now we can access x in the y() function though we did not declare x under the y(). So here child y() can access the parent variable this is called Lexical Scoping.

*Closure: *
Closure just like Lexical Scoping. We did not need to do anything for closure. It’s a default behavior of javascript. When we write a function inside a function then there is a parent child relationship occurring. If we return a parent function we can also access a variable from the parent function into the child function. This is called closure.

Top comments (0)