Functioning Anonymously with JavaScript

By Chris Minnick, Eva Holland

You can create functions in JavaScript. The most common way to create a function in JavaScript is by using the function keyword. Here’s an example of that technique in action:

function myFunction() {
 // do something
}

This function definition creates a function that has a name. Whenever the function is called using the name of the function, it will run:

myFunction();

Another way to create a function is by writing an anonymous function. An anonymous function is a function without a name. For example:

function () {
 // do something
}

At first, this function may seem strange, because there seems to be no way to call it. However, you can assign an anonymous function to a variable, as in this case:

var myFunction = function () {
 // do something
}

When you’ve done this, you can call the function by using the variable name, followed by parentheses, just as you would if you created a named (not anonymous) function. For example:

myFunction();

In practice, both of these methods are usually interchangeable. However, there is an important difference.

Named functions can be called from anywhere in a JavaScript program. If you make a function call to a named function, JavaScript goes looking for the function inside your program.

Anonymous functions assigned to a variable can only be used after the var statement that creates them is run. So, if you try to run a function created in this way before the var statement that names the anonymous function runs, you’ll get an error.

Anonymous function are usually used for cases where you may need to change the function during the program. Changing the anonymous function assigned to a variable is just as easy as changing the value of any variable.

For beginners, anonymous functions can take some time to get used to and to get comfortable with. But if you’re aware of their existence, you’ll be able to recognize them. Eventually, you’ll come to know and appreciate all the many uses for anonymous functions.