How to understand JavaScript module pattern?

JavascriptObject Oriented ProgrammingFront End Technology

JavaScript does not support classes natively, so the Module pattern is used. This is to store public, private methods, and variables inside a single object. To use and understand it, we will workaround Anonymous closure, to display the voters disqualified since they failed in fulfilling the age criteria of 18 years.

Example

You can try to run the following code to understand the JavaScript module pattern

<!DOCTYPE html>
<html>
   <body>
      <script>
         (function () {
            var votersAge = [15, 50, 27, 17, 22, 87, 65, 45];
            var average = function() {
           
            var total = votersAge.reduce(function(accumulator, age) {
               return accumulator + age}, 0);
               return total / votersAge.length + '.';
            }
            var notQualified = function(){
               var notAdult = votersAge.filter(function(age) {
                  return age < 18;});
               return 'Voters not qualified to vote (age less than 18) = ' + notAdult.length;
            }
            document.write(notQualified());
         }());
      </script>
   </body>
</html>
raja
Published on 01-Mar-2018 06:11:23

Advertisements