-2

I saw this on some sample code

var foo = (function(){
    //some code
})();

What does this mean? and how is it different from

var foo = function() {
    //some code
}

I saw that here where the original code was:

var registrationForm = (function() {
    var callbacks = [];

    function inputChanged() {
        // Execute registered callbacks
        for(var i = 0; i < callbacks.length; i++) {
            callbacks[i](isValid());
        }
    }

    function isValid() {
        // Check whether form is valid or not
        return !!(name.value) && !!(dateOfBirth.value) && !!(email.value);
    }

    function getFormData() {
        // Get form values
        return {
            name: name.value,
            dateOfBirth: dateOfBirth.value,
            email: email.value  
        };
    }

    var name = document.getElementById("inpName");
    var dateOfBirth = document.getElementById("inpDob");
    var email = document.getElementById("inpEmail");

    name.addEventListener("change", inputChanged);
    dateOfBirth.addEventListener("change", inputChanged);
    email.addEventListener("change", inputChanged);

    return {
        isFormValid: function() {
            return isValid();   
        },
        getFormData: function() {
            return getFormData();
        },
        attachFormChanged: function(cb) {
             callbacks.push(cb);
        }
    };
})();
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
davidx1
  • 3,525
  • 9
  • 38
  • 65

1 Answers1

-1

That is called an immediately invoked function expression. It's invoked as soon as it's declared, versus the latter, you have to call it to execute it.

Phillip Chan
  • 993
  • 7
  • 17