JavaScript Module pattern provides a way to wrap public, private methods (and variable) into a single entity. The functions or variables defined in a module are not visible outside unless we explicitly export them.
Module basics
ES6 modules are stored in files.There’s no special module keyword.
ES6 modules are automatically strict-mode code, even if we don’t write "use strict"
. We can use import
and export
in modules.
Basic usage
Here very basic example for module export and import. Here we are going to create two utility functions.
generateRandom()
: Generates a random number.
sum()
: Adds two numbers.
We can also rename the values while exporting like this:
Using above utils modules in our main javascript file