JavaScript code not working

Isaac
Isaac used Ask the Experts™
on
Please explain whey the following does not execute.
var counterModule = (function() {
	var counter = 0;
		
	return {
		incrementCounter: function () {
			 counter++;
       alert(counter++);
		},
		resetCounter: function () {
			counter = 0;
			alert("counter value prior to reset: " + counter);
		}
	};
}

counterModule.incrementCounter();
counterModule.incrementCounter();
counterModule.incrementCounter();
counterModule.resetCounter();

Open in new window


https://jsfiddle.net/isogunro/f2qjoqbs/

Thanks!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2010
Commented:
You are missing a )
If you use F12 console, you can see the error.

You also need paranthesis when you call counterModule

counterModule().incrementCounter();

Here's an updated Fiddle:  https://jsfiddle.net/zephyr_hex/q8eowfja/

Next... you may want to use a globally scoped counter variable (move it outside the counterModule function).  Otherwise, the increment isn't additive.
Software Engineer
Commented:
Actually I would expect the intended pattern to be an IIFE because the whole idea would be to create a self-contained class or 'module' to handle the counter functionality. By executing it more than once you lose that functionality. By changing it to use a global variable you're taking a step back instead of forward (in terms of code design).

The corrected code would be:
var counterModule = (function() {
	var counter = 0;
		
	return {
		incrementCounter: function () {
			 counter++;
       alert(counter++);
		},
		resetCounter: function () {
			counter = 0;
			alert("counter value prior to reset: " + counter);
		}
	};
})(); // note the result of the function execution being assigned to the variable instead of a reference to the function itself

counterModule.incrementCounter();
counterModule.incrementCounter();
counterModule.incrementCounter();
counterModule.resetCounter();

Open in new window

Some more errors are left in there (mainly related to the alerts) but I feel they can be resolved more easily once you have the module pattern implemented and working.

EDIT: updated fiddle here
IsaacSharePoint Client Side Developer

Author

Commented:
Thank you!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial