Difficult to debug mistakes with JavaScript modules

Save hours of debugging time by spending 10 minutes learning about how JavaScript modules work

by Lakshay Akula

JavaScript

/* 
	Mistake 1
	- Using "this" keyword in a Module's output
*/

// Object

const objA = {
  value: 2,
  getValue: function() {
    return this.value
  }
};

console.log(objA.value); // 2
console.log(objA.getValue()); // 6

// Module

const moduleA = (function (){
  privateValue = 3
  
  return {
    publicValue: 2,
    getValues() {
      return [this.publicValue, privateValue]
    }
  }
})();

// All good so far
console.log(moduleA.privateValue); // undefined (as expected)
console.log(moduleA.publicValue); // 2
console.log(moduleA.getValues()); // 4 * 3 * 2 = 24


const otherModule = (function() {
  return {
    callback: function(callback) {
      callback();
    }
  }
})();

console.log(otherModule.callback(moduleA.getValues));

/* 
	Mistake 2
	- Using public variables incorrectly
*/
let myWrongModule = (function () {
    var obj = {};
    var arr = [];
    
    var update = function () {
        obj = {key: "value"};
        arr = ["value"]
        };

    var rightUpdate = function () {
        obj.key = "value";
        arr.push("value");
        };

    return {obj, arr, update};
})();


console.log(myWrongModule.obj); // prints {}
console.log(myWrongModule.arr); // prints []

myWrongModule.update();

console.log(myWrongModule.obj); // Still prints {}! We wanted {key: "value"}
console.log(myWrongModule.arr); // Still prints []! We wanted ["value"]

let myRightModule = (function () {
    let obj = {};
    let arr = [];

    let update = function () {
        obj.key = "value";
        arr.push("value");
        };

    return {obj, arr, update};
})();


myRightModule.update();

console.log(myRightModule.obj); // {key: "value"}
console.log(myRightModule.arr); // ["value"]

/* 
	Mistake 3
	- Using primitive-type public variables
*/
let myCounter = (function () {
		
    let count = 0;
    
   	let addCount = function () {
    	count++;
      console.log(`After incrementing, count is now ${count}`);
    }
    
    return {count,...