Declaring a JavaScript function that is inside a variable?-Collection of common programming errors

They do almost the same thing, but there are differences and reasons for having both. The first a function expression because it is assigned to a variable. In addition, unrelated to being a function expression, it is an anonymous function because it does not have a function name. The second one is a function declaration because it is not part of another expression, and is “a source element (non-nested statement in the script or a body function) of a function of the script.” (I don’t quite know how to explain a source element so I copied that from Mozilla docs). It also has a function name, myFunction. In addition, the function can also be used before the function declaration, unlike functions defined by a function expression.

The following example using a function expression will not work:

plusOne(1);
var plusOne = function (x) {
    return x + 1;
};

The following using a function declaration instead, will work:

plusOne(1);
function plusOne(x) {
    return x + 1;
};

In addition, seeing as the topic of the link where you saw this function declaration is closures, I’ll continue on to explain why you may use a function expression and an anonymous function. Sometimes, a function simply doesn’t need a name and can just be anonymous because no one will need to call it by its name. A function expression can be used for something you might have learned about yet, called closures. A closure is when a function encloses variables for use within it at a later time, preventing any outer scope from reaching it. They are a bit difficult to explain, and can also be tough to understand without going through various examples a few times and trying it yourself.

Assuming you have enough basic javascript knowledge (for loops, creating and appending dom elements, and onclick), take for example the following code, which is similar to a problem I encountered before I discovered closures myself. Read through it without running the code first, and try to figure out what will happen when you click each button/div.

function addButtons() {
    for (var i=0; i

Originally posted 2013-11-09 21:03:36.