Finding Closure
An introduction to JavaScript Closures
While trying to expand my knowledge of JavaScript, and preparing for technical interviews I have continued to hear the term closures.The concept of closures in JavaScript seem to be very important due to the fact that employers ask about this very concept on interviews. Understanding what and how to use closures in JavaScript seems like it can make or break a job interview.
What is a JavaScript closure?
A closure gives you access to a parent or outer function’s scope from a child or inner function. In JavaScript, closures are created every time a function is created. Closure means that the inner function will always have access to the variable of its outer function. The function accomplishes this by storing a reference to the outer function’s variables. It does not store the actual value of the variable . The function at creation then has access to variables in three scopes : Variables declared in their own scope, variables declared in a parent function scope and variables declared in the global scope. Closures are nested function which have access to the outer scope after the outer function is returned, by keeping a reference to the inner function (the closure) we prevent the outer scope to be destroyed or lost.
How to use a JavaScript Closure
Below is an example of a basic JavaScript Closure.
function helloName(person) {var hello = "Hello, " + person + "!";var name = function() { var welcome = hello + " Welcome!";console.log(hello);};return name;}var greeting = helloName("Oliver");greeting(); =>> Hello, Oliver. Welcome!
The function Name()
from the example above is the closure in the function.
- The
name()
function has its own local scope with variablewelcome.
- The
name()
function also has access to the outer functions scopehello
from thehelloName()
function.
After the execution of helloName()
function is completed, the scope is not lost or destroyed. The greeting()
function still has access to it. However, there is not other way of accessing the variable from the outer scope except by the closure.The closure Name()
serves as the entrance point between the global scope and the outer scope. We cannot access direct variables from the outer scope if not for the closure.
JavaScript closures at first can be difficult to understand. I believe the ability to understand closures and more importantly know when to use them will make your code cleaner and ultimately make you a better developer . We all need some closure, especially getting ready for job technical interviews.