Skip to content

JavaScript Functions

tdkehoe edited this page May 22, 2015 · 4 revisions

#Creating a Function: Declaration vs. Expression

Functions can either be a variable or a part of a variable. The former is a declaration, the latter is an expression.

Function declaration:

function bar() {
    return 3;
}

Function expressions can be named, anonymous, or self-invoking:

//anonymous function expression
var a = function() {
    return 3;
}

//named function expression
var a = function bar() {
    return 3;
}

//self invoking function expression
(function sayHello() {
    alert("hello!");
})();

If you declare a function as a variable, you don't use the keyword var. The keyword var creates a function expression, i.e., the function is part of the variable.

Function declarations are hoisted, i.e., available in a program before the function is declared.

Function declarations can be used inside non-function blocks, e.g., an if conditional block.

Function expressions are preferred by better coders. Hoisting isn't necessary if the code is written in order.

Function declarations exist alone. Function expressions are part of larger code blocks.

Function expressions are used in functional programming (whatever that is).

Function expressions are usually anonymous (the variable is named, not the anonymous). This can be a problem in debugging. This problem can be avoided by using the same name for the variable and the function:

var today = function today() {return new Date()}

Function expressions can be self-invoking, such as when the webpage loads the JavaScript:

//self invoking function expression
(function sayHello() {
    alert("hello!");
})();

That looks like a function declaration but there are two sets of parentheses (the first pair around the function, the second pair after the first pair).

Clone this wiki locally