What is the expected output?var add = (function ( ) { var counter = 0; return function ( ) { counter += 1; return counter;}})(); console.log(add());console.log(add());console.log(add());Options: Pick one correct answer from below0 0 00 1 10 1 21 2 3
Question
What is the expected output?var add = (function ( ) { var counter = 0; return function ( ) { counter += 1; return counter;}})(); console.log(add());console.log(add());console.log(add());Options: Pick one correct answer from below0 0 00 1 10 1 21 2 3
Solution
The correct answer is 1 2 3.
Here's why:
The function add is an example of a JavaScript closure. A closure is a function that has access to its own scope, the outer function's scope, and the global scope.
In this case, the outer function is an immediately invoked function expression (IIFE) that defines a variable counter and returns an inner function. The inner function increments counter by 1 each time it's called and then returns the new value of counter.
The IIFE is immediately invoked and its return value (the inner function) is assigned to add. So, add is a function that increments counter by 1 each time it's called.
The first time add is called, counter is incremented from 0 to 1 and 1 is logged to the console. The second time add is called, counter is incremented from 1 to 2 and 2 is logged to the console. The third time add is called, counter is incremented from 2 to 3 and 3 is logged to the console.
So, the output of the code is:
1 2 3
Similar Questions
What is the output of following code?var a = 10;function test() { a = 20;}test();console.log(a);Options: Pick one correct answer from below1020
What will be the output of the following code snippet?(function(){ setTimeout(()=> console.log(1),2000); console.log(2); setTimeout(()=> console.log(3),0); console.log(4); })();*1 2 3 42 3 4 14 3 2 12 4 3 1
What will be the output of the following code snippet?var a = 1; var b = 0; while (a <= 3) { a++; b += a * 2; print(b); }*4 10 181 2 3None of Above1 4 7
What will happen, if the following JavaScript code is executed?var count =0; while (count <10) { console.log(count); count++; } Question 2Select one:a.The value of count variable are ogged or stored in a particuar location or storageb.An exception is thrownc.An error is displayedd.The vaue of count from 0 to 9 is displayed in the console
What is the output of this code?function myFunction(a) { console.log(a + b);}const b = 79;myFunction(10);
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.