Category: Closure

Practical Usage of Closure in JavaScript

Closure is a very important concept that every JavaScript developer should understand. In my earlier post, I discussed what is closure and then, some examples to understand this concept. I highly recommend you go through that post and video before going into the details of this post.Blog: Understand JavaScript ClosureVideo: Understand JavaScript ClosureNote – I am sharing all my JavaScript Developer Certification study notes here. Please provide your feedback if you see anything wrong or missing. Appreciate.This post will cover some of the practical use of closures:Private variables and methodsPrivate variables and methods can be implemented using closures.var doOperation = function (value)...

Read More

Understand JavaScript Closure

 Closure is a very important concept that every JavaScript developer should understand. In the post, I will provide a quick introduction of closure and then, I will be focusing on examples so that it will be easier for you to understand this concept. I will be sharing the video as well at the end of this post.Note – I am sharing all my JavaScript Developer Certification study notes here. Please provide your feedback if you see anything wrong or missing. Appreciate.What is a Closure?As per MDN, “A closure is the combination of a function bundled together(enclosed) with references to its surrounding state. In other words, a closure gives you access to an outer function’s scope from an inner function”.With the above example, let’s go through some examples to understand closure in detailsExample 1function sayHello() { var message = “Hello World”; function sayItNow() { console.log(message); } return sayItNow;}var returnFunc = sayHello();returnFunc();Output:Hello WorldExplanation:In the above example, the outer function sayHello creates a variable message, which is then being used inside the inner function sayItNow. Within the inner function, there is no variable declared, but due to closure, it can access the variable declared within the outer function.Example 2function increment() { var number = 10; function printTheNumber() { console.log(number); } number++; return printTheNumber;}var returnFunc = increment();returnFunc();Output:11Explanation:In the above example, the outer function increment creates a variable number, which is then being used inside the inner function printTheNumber. Within the inner function, there is no variable declared, but due to...

Read More
Loading