I’ve been learning about JavaScript revealing module pattern and I ran into this example.
I still do not understand why is this function failNum not a function? How does this code achieve that?
Thanks
var examCalc = (function (gradesArray) {
var grades = gradesArray;
function _failNum () {
var fails = grades.filter(function(item) {
return item < 6;
});
return 'You failed ' + fails.length + ' times.';
}
function average () {
var total = grades.reduce(function(accumulator, item) {
return accumulator + item;
}, 0);
return 'Your average is ' + total / grades.length + '.';
}
return {
grades: grades,
average: average
}
})([9, 5, 8, 9, 5, 7]);
console.log(examCalc.grades);
console.log(examCalc.average());
console.log(examCalc._failNum())
Just like variables inside a function are private, so too are functions inside them. So unless you return something which provides access to the inner function, it’s only accessible inside the IIFE
So I choose which functions inside another function I want to be private, and which public? Right?
At the end of examCalc function I added to into the object
_failNum: _failNum
and it works.
By putting it in a return statement I make it public.