JS-Closure Questions.

Total Number of Questions: 8
  1.

function counter(){
 var counter = 0;
 function IncreaseCounter() {
  return counter += 1;
 };
 return IncreaseCounter;
};
var counter = counter();
alert(counter());
alert(counter());
alert(counter());
alert(counter());

Code:-
Alert with values 1,2,3,4.

  2.

let count = 0;
(function () {
 if (count === 0) {
  let count = 1;
  console.log(count); // What is logged?
 }
 console.log(count); // What is logged?
})();

Code:-
1

  3.

for (var i = 0; i < 3; i++) {
 setTimeout(function log() {
  console.log(i); // What is logged?
 }, 1000);
};

Code:-
3 gets logged 3 times with 1 sec difference between each log.

  Operations in Inner functions.

Write a code to calculate area of a rectangle using inner function. In this case outer function should accept parameter length and inner function should accept parameter breadth.

Code:-

  Inner-Outer Function relation.

Take a variable in outer function and create an inner function to increase the counter every time it is called.

Code:-
function counter()
var counter = 0;
function IncreaseCounter(){
    return counter +=1;
}
return IncreaseCounter;
}
var counter = counter();
alert (counter())
alert (counter())

  What will be the Output?

var a = 12;
(function () {
 alert(a);
})();"

Output:-
Alert with value as 12.

  What will be the Output?.

var a = 10;
var x = (function () {
 var a = 12;
 return function () {
  alert(a);
  };
 })();
x();

Code:-
Alert with value as 12.

  4.

var globalVar = ""xyz"";
(function outerFunc(outerArg) {
 var outerVar = 'a';
 (function innerFunc(innerArg) {
  var innerVar = 'b';
  console.log(
  ""outerArg = "" + outerArg + ""\n"" +
  ""innerArg = "" + innerArg + ""\n"" +
  ""outerVar = "" + outerVar + ""\n"" +
  ""innerVar = "" + innerVar + ""\n"" +
  ""globalVar = "" + globalVar);
 })(456);
})(123);

Code:-
outerArg = 123
innerArg = 456
outerVar = a
innerVar = b
globalVar = xyz