JavaScript – How to make a module in JS

Making a module in JS is kind of interesting. Especially, if you expect something like a class like in VBA or C#. Well, it has nothing to do with it, it is just a function, assigned to a variable.

In the current article, I simply make one small module and I print it. The trick is in the nested functions in the module, which return what you have asked for … In a way! 🙂

Thus, I have asked to create two articles, with dates and titles. Then I change the title of the second article (in an array we start counting from zero). Then I print what I have. The interesting thing is that in any other language (C#, VB or anything powered by .Net or Java engine) I would have expected to see two different versions of the array named “articles”. However, in JS this is not the case 🙂

Check out what do I mean here:

js_module

Yup, this is how it looks like! 🙂 JS is fast like the wind in its own way!

Here comes the code:

<!DOCTYPE HTML>
<html>
    <head>  
    </head>
	<body>
		<script type="text/javascript">
		// Example of modules in JavaScript
			'use strict';
			var vitoshacademy = (function(){

				var articles = [];

				function letArticles(date, title){
					articles.push([date,title]);
				}

				function changeArticleTitle(number, newTitle){
					articles[number][1] = newTitle;
				}

				function getArticles(){
					return articles;
				}

				function deleteArticles(){
					articles = [];
				}

				return{
					la: letArticles,
					ga: getArticles,
					ca: changeArticleTitle,
					de: deleteArticles
				};
			})();
			vitoshacademy.de();
			console.log(vitoshacademy.ga());
			vitoshacademy.la("12/12/2015","How to code?");
			vitoshacademy.la("12/12/2016","How to code even better?");
			console.log(vitoshacademy.ga());
			vitoshacademy.ca(1,"Changed article title to this");
			console.log(vitoshacademy.ga());
		</script>
    </body>
</html>

Available also in GitHub here!