As an addition to Elliot Bonneville's answer, you can also do this:
var firstFunction = (function()
{
var counter = 0,
secondFunction = function
{
counter++;
};
return function()
{
counter = 0;//initialize counter to 0
secondFunction();
return counter;
};
};
console.log(firstFunction());//logs 1, because counter was set to 1 and returned
This is all getting a bit much, but google "JavaScript module pattern" and look into it. You'll soon find out what makes this code tick:
var counterModule = (function()
{
var counter = 0,
secondFunction = function
{
counter++;
},
firstFunction = function()
{
counter = 0;//initialize counter to 0
secondFunction();
},
getCounter = function()
{
return counter;
}
setCounter = function(val)
{
counter = +(val);
};
return {firstFunction: firstFunction,
getCounter: getCounter,
setCounter: setCounter};
};
console.log(counterModule.firstFunction());//undefined
console.log(counterModule.getCounter());//1
console.log(counterModule.secondFunction());//ERROR
It's all about exposure of certain closure variables... Keep working at it, this is an important pattern to understand, I promise!