javascriptfunction

JavaScript & self executing functions


I'm trying to understand (probably simple concepts) about JS, and I've put together the below piece of code to explain what I don't get. What I do not understand is where the name variable is stored. Is that variable now global?

(function($) {

  var name = '';

  $.helloWorld = function(yourName) {
    name = yourName;
    console.log("Hello " + yourName);
  }

}(jQuery));

Solution

  • The name variable is local to the outer function, because it's declared with the var keyword. The inner function is a closure that contains a reference to that variable. Here's a better example that shows this off:

    (function($) {
    
      var name = '';
    
      $.setName = function(newName) {
        name = newName;
      }
    
      $.showName = function() {
        console.log("Name is: " + name);
    
    }(jQuery));
    

    After defining this, you can do:

    $.setName("Larry");
    $.showName();
    $.setName("Fred");
    $.showName();
    

    See How do JavaScript closures work?