JS Interview Question: What is a closure, and how/why would you use one?

What is a closure, and how/why would you use one?

RLyn Ben
2 min readJan 12, 2016

--

Closures are inner functions inside of an outer function. They have their own local scope and has access to outer function’s scope, parameters (but NOT arguments object), and they also have access to global variables.

From what I understand, Closures is a neat way to deal with scope issues. Reasons we use Closures is because Javascript is a function-level scope rather than as with other languages, block-level scope and Javascript is an asynchronous/event driven language. Example that Closure is frequently used is jQuery (ex. click()).

This is how Closures work.
1. After its outer function has been executed and has returned a value, closures can still run.
2. Closures store references to the outer function’s variable, hence, we will always have access to the updated values of outer function’s variables.
3. Since we have access to the updated values of outer function’s variables. We will have issue/bugs when a variable changes via for loop, but this can be fixed by using IIFE, Immediately Invoked Function Expression.

Below is a sample code of using Closure with IIFE.

  • Note, IIFE or Immediately Invoked Function Expression is another Javascript concept.

Also

If you are looking for a platform to develop your clients’ website, check out my SAAS platform https://ecompurpl.com :)

EcomPurpl.com is the all-in-one solution for anyone looking to create a website. Templates, E-Commerce, Hosting, Galleries, Booking & Appointments, CRM, 24/7 support, and integration of your app are all included.

--

--

RLyn Ben

Software Engineer / Front-End Dev. Currently resides in Las Vegas. https://ecompurpl.com