JavaScript Scopes and Closures

JavaScript Scopes and Closures

Understand Scopes and Closures in JavaScript

Β·

7 min read

Play this article

Hey Learners! This is SHIVAM :)

Today, we will understand Scope and Clousers in JAVASCRIPT. Scopes are a very important thing in "JavaScript", and to understand "Closures"(which is a very important topic in JavaScript), we have to get a clear understanding of scopes. So, today we will learn about:

  • Scopes
  • Types of Scopes
  • Closures

So, let's start without wasting any time.

SCOPES

In simple terms "Scopes determine the accessibility of variables".

Scoping is determining where variables, functions, and objects are accessible in your code during runtime. This means the scope of a variable(where it can be accessed) is controlled by the location of the variable declaration.

Now, this is just the definition of the scopes but, we will understand scopes through their types.

  • There are 3 types of scopes in JavaScript:

  • Block Scope

  • Function scope
  • Global scope

3 Types Of Scopes

So, we will start with Block Scope.

So, Before ES6, JavaScript had only Global and Function Scope.ES6 introduced two important new JavaScript keywords: let and const.

These two keywords provide Block Scope in JavaScript.

Variables declared inside a block { } cannot be accessed from outside the block are called block scope.

If you declared any variable using "let" and "const" then, that variable will going to have some block scope.

  • Example πŸ‘‡
{
let val = 34;
}
// Now, you cannot use "Val" here, because you declared a variable with "let" which is a  Block Scope Keyword
{
var val = 36;
}
// but, you can use "Val" here because you declared a variable with "var" which is not a  Block Scope Keyword

Now, after "Block Scope" there is one thing named "Local Scope".

Variables declared within a JavaScript function, become LOCAL to the function.

  • Example πŸ‘‡
// code here can NOT use varName

function myFunction() {
  let varName = "JavaScript";
  // code here CAN use varName
}

// code here can NOT use varName
  • So, local variables are only recognized inside their functions, variables with the same name can be used in different functions. Local variables are created when a function starts and deleted when the function is completed.

Now, let's understand Function Scope

Function Scope

A function scoped variable means that the variable defined within a function will not accessible from outside the function

Note Variables declared with var, let and const are quite similar when declared inside a function.

Example πŸ‘‡

function funcName() {
  let subject = "JavaScript";   // Function Scope
}
// Instead of "let" you can also use "var" or "const". They will work the same.

In the above example, you cannot access "subject" outside the function, because it is declared inside the function. If you try to access "subject" outside the function like this.πŸ‘‡

2022-06-17 (2).png

You will get an error on your console that "subject is not defined" like this πŸ‘‡

2022-06-17 (1).png

So, this is the "Function Scope". Now, let's understand Global Scope.

Global Scope

If you understand the "Function Scope" then, the "Global Scope" is just a Piece Of Cake.

A variable declared outside a function, called GLOBAL Variable.

Example πŸ‘‡

2022-06-17 (4).png

As you can see in the above image, I declared a variable named "subject" outside the function(which is now we can say a "Global Variable"), so we can access it anywhere. You can see above that I used it inside the function as well as outside the function.

So, when you call the function you will get the output "JavaScript", and after the console log the "subject" variable you will again get the output "JavaScript". The output will look like this.πŸ‘‡

2022-06-17 (3).png

Now, there is one more thing in this "Global Scope" is that, if you assign any value to a variable without declaring it, then that variable will become a "Global Variable" automatically.

Example πŸ‘‡

2022-06-18 (1).png

As you can see in the above image, I assigned a value "JavaScript" to the variable "Subject" without using any variable keyword(var, const, let), So in this case the variable will automatically become a "Global Variable", and we can use it anywhere(you can see in the above image I use "subject" variable 3 times.

Note- if you don't want this type of declaration you can use "use strict" at the top of your "JavaScript" file.

"use strict";

//now you can't assign value to any variable without declaring a variable.

So, these are the scopes in"JavaScript". Now, let's see about "Closures".

What are Closures?

First of all, Closures are an extremely important topic in JavaScript, most of the interviewers ask about this in interviews. So, be focused while learning. Now, let's start with the definition.

A closure is a function, that has access to "Parent Scope", even after the parent function has closed.

A closure is created when we define a function, not when we create a function

So, let's understand with an example.

Example Of ClosuresπŸ‘‡

2022-06-18 (3).png

  • Now, as you see in the image, firstly I declared a variable num and assigned a value "4".

-Then, I made a function named "parentFunc". Again, I declared a variable named parentVal.

  • Then, I console log both the variable.

  • Now, I made one more function inside a parent function named, childFunc.

  • Inside the childFunc, I console log the variable's value by some incrementation.

  • Then, I am calling the childFunc inside the parentFunc.

  • And, at last, I am calling parentFunc.

So, here when I am calling a parentFunc, it will first print parentVal variable(which is 3), then it will print num variable(which is 4).

  • Now, the child function will be called, and inside the child function firstly print num(which will now become 14), and then parentVal will print i.e 23

So, the output will look like this. πŸ‘‡

2022-06-18 (4).png

  • Now, this is not an example of closures because if you look at the definition that I have written above and, focus on the last part which says that has access to "Parent Scope", even after the parent function has closed, then you understand that, in this example, child function has no access to parent function after closing the parent function.

So, to get the access to the parent function through the child function, we have to do thisπŸ‘‡

2022-06-18 (5).png

Now, here you can see that instead of calling the "child function" inside the "Parent Function", we are returning the child function, and saving the "Parent Function" into a new constant variable named result.

So, just after writing this lineπŸ‘‡ you can see that the output will be 3 and 4.

const result = parentFunc(); //this will going to print 3 and 4 only

You can see that, we don't get any output from our child function. This is happening because we are returning the function. If you write this line πŸ‘‡.

console.log(result);

The output will look like thisπŸ‘‡.

2022-06-18 (6).png

Here you can see that the result contains the whole child function. So when you call result like this πŸ‘‡

2022-06-18 (7).jpg

  • You will get this output πŸ‘‡

2022-06-18 (4).png

  • Now, here you can see that our Parent Function is already closed but, our child function still can access their parent function, and that makes our value a private variable that only child function has access to.

  • Now if you call result again it will be going to increment the value. You can see it here πŸ‘‡

2022-06-18 (8).png

the output will look like thisπŸ‘‡

2022-06-18 (9).png

  • Now it means that result has access to the global scope which is a public variable but it also has access to the scope of its parent function which is a private variable.

  • So, that is a great way to make a private variable, and that is the Closure, because we have access to the scope of the parent function even after the parent function has returned.

Thank You

I hope these examples help you to understand "Scopes" and "Closures" If you learn something from this, do share it with your friends and others.

Hope You Enjoy Reading :)

Group 4809601441522.png

Try it for free

Did you find this article valuable?

Support Fueler Blog by becoming a sponsor. Any amount is appreciated!

Β