I have the following function in my counter.js file:
//counter.js
var counter = 1;
function increment() {
counter++;
}
function decrement() {
counter--;
}
function getCounter() {
return counter;
}
module.exports = {
counter: counter,
increment: increment,
decrement: decrement,
getCounter: getCounter
};
In my main.js, I have the following code:
//main.js
var counter = require('./counter');
counter.increment();
console.log(counter.counter); // 1
console.log(counter.getCounter()); // 2
I am unable to understand, why does the
counter.counter
gives 1 as output, whereas the
counter.getCounter()
gives 2 as the output.
What is the possible explanation for this behavior?