Q
What will be the output of the following code? var counter = (function() { var count = 0; return function() { return ++count; }; })(); console.log(counter()); console.log(counter());

Answer & Solution

Answer: Option A
Solution:
The IIFE returns a function that increments count and returns it. The first call to counter() returns 1, and the second returns 2.
Related Questions on Average

How can you store a function as a property of an object?

A). var obj = { method: function() { alert('Hello'); } };

B). var obj = { method: alert('Hello'); };

C). var obj = { method: function { alert('Hello'); } };

D). var obj = { function() { alert('Hello'); } };

What will be the output of the following code? var double = function(x) { return x * 2; }; console.log(double(5));

A). 10

B). 5

C). undefined

D). double

How do you define an anonymous function assigned to a variable?

A). var anon = function() { alert('Anonymous!'); };

B). var anon = function { alert('Anonymous!'); };

C). function anon() { alert('Anonymous!'); }

D). var anon = function anonymous() { alert('Anonymous!'); };

What will be the output of the following code? var add = new Function('a', 'b', 'return a + b'); console.log(add(2, 3));

A). 5

B). add

C). undefined

D). 2 3

Which of the following is true about functions in JavaScript?

A). Functions can be assigned to variables

B). Functions can be passed as arguments to other functions

C). Functions can be returned from other functions

D). All of the above

What will be the output of the following code? var sayHi = function() { return 'Hi'; }; console.log(sayHi());

A). Hi

B). undefined

C). sayHi

D). function

What is the output of the following code? function makeAdder(a) { return function(b) { return a + b; }; } var add5 = makeAdder(5); console.log(add5(2));

A). 7

B). 5

C). add5

D). makeAdder

How do you assign a function to a variable in JavaScript?

A). var greet = function() { alert('Hello'); };

B). var greet = function { alert('Hello'); };

C). function greet() { alert('Hello'); }

D). var greet = function alert('Hello');

Which of the following correctly demonstrates a function returning another function?

A). function outer() { return function() { alert('Inner'); }; }

B). function outer() { function() { alert('Inner'); } return; }

C). function outer() { function() { alert('Inner'); }; }

D). function outer() { return function { alert('Inner'); }; }

What will be the output of the following code? var multiply = (x, y) => x * y; console.log(multiply(3, 4));

A). 12

B). 34

C). multiply

D). undefined