Closure function is a part of advanced javascript, It is basically used to access outer function parameters and variables in the inner function so this inner function is called closure function.
the inner function returns into the outer function.
Suppose, you have a outer function start() and declared employeeName variable in this and called this variable into displayEmployeeName() inner function.
function start() {
var employeeName = 'John'; // employeeName is a local variable created by start function
function displayEmployeeName() { // displayEmployeeName() is the inner function, a closure
console.log("Hello "+employeeName); // employeeName variable declared in the parent function
}
displayEmployeeName();
}
start();
Suppose, you have defined x variable value into the outer scope and captured the x variable value into inner scope function getNum()
var x = 5; // declaration in outer scope
function getNum() {
console.log(x); // outer scope is captured on declaration
}
getNum(); // prints 5 to console
Suppose, You change the outer scope variable x value into the inner function scope then the value will be change.
var x = 5; // declaration in outer scope
function getNum() {
x=2;
console.log(x); // outer scope is captured on declaration
}
getNum(); // prints 2 to console
Javascript Closure function – Interview Questions
Q 1: What is closure?
Q 2: Why closures are used?
Q 3: Do closures store variables?
Q 4: Are closures memory-heavy?
Q 5: Example use?
Javascript Closure function – Objective Questions (MCQs)
Q1. A closure is created when a function ______.
Q2. Closures allow access to ______ variables.
Q3. Closures are commonly used for ______.
Q4. Variables in closures are preserved in ______.
Q5. Which feature enables closures?