Responsive Advertisement

JavaScript #4: Closure in JavaScript


You've heard about closures in JavaScript but you haven't grasped it. Or you haven't heard of the concept of closure. Here's an article to help you understand closures and make them applicable.

Table of contents:

    What is closure in javascript?

    Creating a function is not closure

    Apply closure

To be able to understand this article well, you need to have a solid understanding of scope in JavaScript. I already have two parts about scope, you can read before getting to the concept of closure.

Scope in JavaScript - Part 1

Scope in JavaScript - Part 2

What is closure?

Let's talk about the definition of closure. Imagine that the generated function will be given its own memory area as if your house had its own address. And your house will not be trespassed can use the resources inside your house. Just as you and your family will be protected.

When you and your family members go out of the house, always remember the way back to your house. When asking you and your family about where your house is, you and your family will surely indicate the exact location and address of your house.

The definition of closure is like the example above, the function is created and allocated its own memory to store and execute. Variables, functions in the function when called outside the scope of the function always remember and about the function to execute.

In addition to the scope, the variables in the closure can look to the parent scope to find the values ​​to use.

Creating a function is not closure

Take a look at the following problems:

let a = 0

function counterA() {

    a++

    console.log(a)

}

 

counterA() // => 1

counterA() // => 2

counterA() // => 3

You want to create a function to increment let a. You call 3 times and the variable a is incremented 3 times. But the problem is that variable a is a global variable that is not in the scope of function counterA(). The variable a is only lost when the program or website ends or refreshes. Thus, private and closure are not shown. So this example is not called a closure.

You will have a thought that if you put the variable a in the function counterA(), it is private and closed. And here is the answer to your question.

function counterA() {

    let a = 0

    a++

    console.log(a)

}

 

counterA() // => 1

counterA() // => 1

counterA() // => 1

Although called as above, since the variable a is in the local scope of the counterA() function, the value will be reset after the function is completed. Function is essentially a closure because it's private and closed, but in this case it doesn't achieve what we originally intended. The conclusion is that this is not a closure and does not achieve the desired result.

Apply closure

So let's take a look at what is a correct closure.

Take a look at the example below.


function doLogger() {

    let a = 0

}

 

console.log(a) // => Uncaught ReferenceError: a is not defined

Function is also a closure. You will see the private and closed properties of the function, outside the function when executing it will not be able to call the variable in the function.

To do closure-style variable increment, how would you do it? Here is the answer for you.

function counterA() {

    let a = 0

    function increaseA() {

        return ++a

    }

    return increaseA

}

const count = counterA()

 

console.log(count()) // => 1

console.log(count()) // => 2

console.log(count()) // => 3

I will explain to you about this function and how it works. You have a function counterA() in which you have variable a and function increaseA(). In function increaseA() return ++a.

The first is the counterA() function, which guarantees to be private. The external environment cannot use the variable a and function increaseA().

const count = counterA(), the count variable will refer to the return content of the counterA() function. Which means variable count now equals function increaseA().

Then you execute the count() function. You will perform the increment of variable a. By definition, the variable a knows where it was created and refers to it. In this case the variable a will jump outside and refer to the outer let a variable. But still express private in a function.

The variable a is called but is not lost because it is referenced by another function. The variable a still stores the value after incrementing. This variable a is lost when the program or website ends or refreshes.

Let's look at another example, when you and your family send a letter to each other, it will include a signature and the content of the message according to the syntax "[signature]- {content}", asking how to create a function that everyone can use but still create their own signature and unique content:

function writeSignature(signature) {

    function writeContent(content) {

        console.log(`[${signature}]- ${content}`)

    }

    return writeContent

}

 

const father = writeSignature('father')

const mother = writeSignature('mother')

const son = writeSignature('son')

const daughter = writeSignature('daughter')

 

father('I will finish working at 6:00pm')

// => [father]- I will finish working at 6:00pm

mother("I'll prepare for the dinner")

// => [mother]- I'll prepare for the dinner

son('Yes sir and madam')

// => [son]- Yes sir and madam

daughter('Yes mom')

// => [daughter]- Yes mom

Excellent! You just create function writeSignature() and writeContent(). Everyone can reuse it. This is pros of closure and apply in many stuffs if you can clearly comprehend.

Besides the above examples, you can also apply closures to many other, more specific cases. The purpose is to reuse code and reduce the number of lines of code.

Cons

Closure still has the disadvantage that is about memory. It cannot be deleted during the running of the program or the website. So, consider and use closure when you really understand it.

Conclusion

Through the article about closures in JavaScript, you have grasped the concept of closures. Closure is a private function, referenced by other functions and always exists until the program terminates.

If you have any comments, feel free to comment below. Thank you for joining with me. Have a good day!


Đăng nhận xét

0 Nhận xét