JS - Use the closure to protect global variables

08 Oct 2020

In JS, sometimes, you want to make a variable private, prevent it to direct get from outside. Recently, I found I can use closure to do that:

var person = (function(){
  var data = {
    name: null
  }

  function setName(personName) {
    data.name = personName;
  }

  function name() {
    return data.name;
  }

  return {
    setName: setName,
    name: name
  }
})();

console.log(person.name()) // null
person.setName('john')
console.log(person.name()) // 'john'
Back to top