Search code examples
javascriptclosuresiife

Creating Private Variables with and without Closures


Recently, I have been trying to learn about private variables and closures in JavaScript. I just learned about IIFEs and how they can be used with closures to create "private" variables and functions. Below is an example I understand.

let test = (function() {
  
  let name = "";
  
  let getName = function() {
    return name;
  }
  
  let setName = function(newName) {
    name = newName;
  }
  
  return {
    getName: getName,
    setName: setName
  };
  
})();

test.setName("Bob");
test.getName(); // "Bob"
test.name; // undefined

However, this leaves me wondering, why couldn't I have just done this with a regular function expression, and then invoked the expression and then just saved that to a variable. This new variable would also have a private name value. For example:

let test2 = function() {
  
  let name = "";
  
  let getName = function() {
    return name;
  }
  
  let setName = function(newName) {
    name = newName;
  }
  
  return {
    getName: getName,
    setName: setName
  };
  
}

let test3 = test2();

test3.setName("Bob");
test3.getName(); // "Bob"
test3.name; // undefined

Is there some benefit to the IIFE method vs a regular function expression that I just invoke right after I define it?

Thanks!


Solution

  • The benefit is that an IIFE is just an expression. No changes are made to the enclosing namespace (well, at least not by the IIFE itself directly). It's useful when you need a scope in order to do some work, but you're in a context that only allows a single expression. The IIFE can be anything, a complete program perhaps, but it returns a single value for the enclosing context (like an object initializer, for example).