1.
function counter(){
var counter = 0;
function IncreaseCounter() {
return counter += 1;
};
return IncreaseCounter;
};
var counter = counter();
alert(counter());
alert(counter());
alert(counter());
alert(counter());
function counter(){
var counter = 0;
function IncreaseCounter() {
return counter += 1;
};
return IncreaseCounter;
};
var counter = counter();
alert(counter());
alert(counter());
alert(counter());
alert(counter());
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?
})();
let count = 0;
(function () {
if (count === 0) {
let count = 1;
console.log(count); // What is logged?
}
console.log(count); // What is logged?
})();
1
3.
for (var i = 0; i < 3; i++) {
setTimeout(function log() {
console.log(i); // What is logged?
}, 1000);
};
for (var i = 0; i < 3; i++) {
setTimeout(function log() {
console.log(i); // What is logged?
}, 1000);
};
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.
Inner-Outer Function relation.
Take a variable in outer function and create an inner function to increase the counter every time it is called.
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);
})();"
var a = 12;
(function () {
alert(a);
})();"
Alert with value as 12.
What will be the Output?.
var a = 10;
var x = (function () {
var a = 12;
return function () {
alert(a);
};
})();
x();
var a = 10;
var x = (function () {
var a = 12;
return function () {
alert(a);
};
})();
x();
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);
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);
outerArg = 123 innerArg = 456 outerVar = a innerVar = b globalVar = xyz