Module Patterns

Hey, I was reading about: https://dev.to/tomekbuszewski/module-pattern-in-javascript-56jm Code snippet:
const Formatter = (function() {
let timesRun = 0;

const log = (message) => console.log(`[${Date.now()}] Logger: ${message}`);
const setTimesRun = () => {
log("Setting times run");
++timesRun;
}

const makeUppercase = (text) => {
log("Making uppercase");
setTimesRun();
return text.toUpperCase();
};

return {
makeUppercase,
timesRun,
}
})();
const Formatter = (function() {
let timesRun = 0;

const log = (message) => console.log(`[${Date.now()}] Logger: ${message}`);
const setTimesRun = () => {
log("Setting times run");
++timesRun;
}

const makeUppercase = (text) => {
log("Making uppercase");
setTimesRun();
return text.toUpperCase();
};

return {
makeUppercase,
timesRun,
}
})();
console.log(Formatter.makeUppercase("tomek"));
console.log(Formatter.timesRun);
console.log(Formatter.makeUppercase("tomek"));
console.log(Formatter.timesRun);
Why do we get timesRun zero, shouldn't it be 1? why is the public value different, im in a position to just "know" but cant explain this very well
8 Replies
13eck
13eck3mo ago
Because timesRun is what’s called a primitive value, so when you’re returning your object it’s making a copy of the number 0. You want to, instead, include a function that returns the current value instead.
brr
brrOP3mo ago
oh its the pass by reference and value thing right?
13eck
13eck3mo ago
Yep
brr
brrOP3mo ago
i see and why is it primitive 😃
13eck
13eck3mo ago
MDN Web Docs
Primitive - Glossary | MDN
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties. There are 7 primitive data types:
13eck
13eck3mo ago
Because it’s not an object
brr
brrOP3mo ago
ok its int alright thank you
brr
brrOP3mo ago
No description

Did you find this page helpful?