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?
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.
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.
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.