Closure - Quick JavaScript Interview Questions (2015)

Quick JavaScript Interview Questions (2015)

Chapter 3. Closure

Q. What is Closure?
A closure is an inner function that has access to the outer wrapped function’s variables. It has three different scope accesses:- Self-scope:
It has access to properties present in its own scope.
Wrapped function’s scope:
It has access to the properties present to from its enclosing function.
Global Scope:
It has access to the properties present in global scope that is window scope.
The inner function still has the access to prop1 though prop1 belongs to outer function scope.

function myOuterFunction(){ var prop1 = 5;
return function innerFunction(){

return prop1;
var res = myOuterFunction(); console.log(;

Below screenshot shows the output of the above code in the console.

Q. Give an example of practical implication of closure concept? ANSWER
In web page development closures are more frequently used by the developers. A most common scenario is when we need some kind of factory which will return a function object with different value that can be used by application.
The following code has a background color factory named backgroundColorFactory which returns a function with an input color. Using this factory we have created greenBackground and blueBackground function objects and binded with the 2 buttons. Once user clicks these buttons the background color of the body is changed to the targeted color.

<!DOCTYPE html>

<meta charset="utf-8">
<title>Practical Closure Example</title>

<button id="greenButton">Green Background</button> <button id="blueButton">Blue Background</button> <script>

var backgroundColorFactory = function(color) { return function() { = color; };
var greenBackground = backgroundColorFactory('green'); var blueBackground = backgroundColorFactory('blue');

document.getElementById('greenButton').onclick = greenBackground;
document.getElementById('blueButton').onclick = blueBackground;

The output of the above code is listed in below screenshot.

Q. Emulate the private data using closure?
The following code demonstrates the declaration of private variable _name. It means we can assign the _name value using Student constructor with a new keyword.

function Student(name) { var _name = name;

this.getName = function() { return _name;

var student1 = new Student("Sandeep"); student1 ._name = "John";

The details of the previous code are as follows:
A Student object student1 is created with _name has value Sandeep.
A new name value John is assigned to _name but the getName() method prints Sandeep to the console. It proves _name is private.

The following screenshot shows the Chrome console with the output of the previous code.