JAVASCRIPT

JavaScript Functions

Function Statement

The natural function declaration or statement is what new JavaSript developers are introduced to.

function helloWorld() {
    console.log("Hello World");
}

helloWorld(); // logs "Hello World" to the console.

Function Expression

var message = "Hello World";

var helloWorld = function() {
    console.log(message);
}

helloWorld(); // logs "Hello World" to the console.

Immediately Invoked Function Expression (IIFE)

Executes the function immediately upon it’s creation. The parentheses () for immediately invoking the function are contained in the outer parentheses. The outer parentheses make the function a function expression.

(function() {
    var message = "Hello World";

    console.log(message);
})();

The parentheses () for immediately invoking the function is contained in the outer parentheses. This behaves the same, it is just a styling preference.

(function() {
    var message = "Hello World";

    console.log(message);
}());

DOMContentLoaded Document Event Example

(function() {

    var message = "Hello World";

    function onDocumentReady() {
        console.log(message);
    }

    if (document.readyState !== "loading") {
        onDocumentReady();
    } else {
        document.addEventListener("DOMContentLoaded", onDocumentReady);
    }

}());
comments powered by Disqus