Module Pattern in JavaScript

·

1 min read

  • It is a commonly used Design Pattern which is used to wrap a set of variables and functions together in a single scope.

  • Using this pattern we can make some vars,function accesibility within a function.

Ex: var is function scoped so here we can use it for the DATA hiding .

function EmployeeDetails() {
  var name: "Mayank";
  var age = 30;
  var designation = "Developer",
  var salary = 10000;



  return {
    name: name,
    age: age,
    designation: designation
  }
}

var newEmployee = EmployeeDetails()

// This will result in "undefined" value
var userName = newEmployee.salary;

USE Case: 1) In preventing our JS vars , objects aceesible by a attacker at client side . As Variables in JavaScript are in the global namespace by default. The variables which are in the global scope can lead to security flaws. Functions that are in the global scope are also dangerous.