Private_or_public

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())

The object assigned to examCalc (the object in the function’s return statement) only has the grades and average properties.

1 Like

This is an example of an IIFE: https://developer.mozilla.org/en-US/docs/Glossary/IIFE

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

1 Like

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.

Yes, that’s right

It’s important to note that IIFEs aren’t the only way to do this, in more modern style JavaScript we can use modules

Yes, I realised one of the future ‘lessons’ I will have to go through are modules.
Thanks a lot.