Introduction

Creating functions is an extremely common routine beginner to advanced developers do all time in their programs. Functions are one of the building blocks of computer programming, and a topic which enjoys a lot of viewership in JavaScript owing to some pretty strange features the language bundles functions with.

In this chapter we shall understand the syntax and logic of creating functions in JavaScript along with some wierdly common terms. Specifically, we'll be understanding what are function declarations and how to use them to create named functions; and the idea of function expressions.

Let's begin!

Function declaration

The simplest and most intuitive way to create functions in JavaScript is using the function declaration syntax. It's analogous to creating functions in some other programming languages.

Here's how it looks like:

function nameOfFunction() {
    // block of code
}

First comes the function keyword to instruct the interpreter that we are about to create a function.

Then follows the name of the function. Since functional identifiers are also variables in JavaScript, all the rules that apply to variable naming also apply to function naming.

After the name we have a pair of () parentheses, that serve a special purpose as we shall explore in the next chapter.

Finally comes a block of code given by the { and } curly braces. Formally, we call this the body, or definition of the function.

A function's body simply contains all the code to be executed when the function is called.

This successfully creates a function; more precisely a named function.

JavaScript has two classifications of functions - named and anonymous. Named functions have a name following the function keyword whereas anonymous functions are without a name.

The theory is clear - to create a named function just use the function declaration syntax, that's it!

There's no other way to create named functions, other than the function declaration syntax.

This completes the general form of creating a function using the function declaration syntax. Although it misses on the important concept of function parameters, this form allows you to grasp a basic overview of how to create functions in JavaScript.

Let's now shift this placeholder notation and create an actual function out of it - a function to give us a warm welcome!

function sayHello() {
    alert("Hello Programmer!");
}

When this function will be executed, an alert will be made shouting "Hello Programmer!" to our ears!

But how do we execute a function?

Before we answer this let's clarify some commonly used terms. Formally we use the word 'call', and even more formally, the word 'invoke' to indicate the idea of executing a function. Hence to 'invoke sayHello()' means to 'execute sayHello()'.

So moving back to our question - to call/invoke/execute a function in JavaScript, first write the name of the function and then append it with a pair of () parentheses.

Shown below is the general form of calling a function:

nameOfFunction()

Using this, now let's call our old function sayHello() and get the long-awaited greeting!

// invoke the function
sayHello();

First we have the name of the function - sayHello and following it a pair of parentheses.

Run this code on your machine (including the definition of sayHello()) and witness the beginning of what is one of the most fundamental, yet powerful concepts of computer programming - functions.

Function expression

Although it's very easy to create functions in JavaScript by declaring them, the language also allows us to do the same job by rather assigning functions. This is commonly known as function expressions.

A function expression is much like, in fact the same, as creating variables. First we have the var keyword, followed by the name of the variable and finally the value to be assigned to it.

In this case the value is a function expression (an expression whose value is a function) and thus the variable, in effect, becomes a function.

Following is the general form:

var nameOfFunction = function() {
    // block of code
}

As before, let's now transform this into an actual example:

var sayHello = function() {
    alert("Hello Programmer!");
}

Talking about the notation to invoke the function in this case - it's exactly the same as before:

// invoke the function
sayHello();

Function declaration vs. expression

At this point you might be thinking: 'if I can create a function by declaring it why do I even need a function expression?'.

This question is legit and yields one of the most exciting and interesting discussion on JavaScript functions which we are about to begin. Let's start by discussing on the purpose of declarations.

Function naming

A function declaration is mainly used to create named functions. As ve've said before, the names follow the same rules as do the names for variables - no special characters, no periods, no starting numerals and so on.

For a detailed guide on variable naming please read the JavaScript Variable Naming chapter.

There is a fine line between functions that have a name and functions that are assigned to named identifiers, but have no name themselves. The former can only be achieved using a function declaration; with the latter being put up in the discussion up next.

However a function declaration can't meet all requirements of creating a function. In many cases we ought to use an expression instead.

Let's consider an example. Suppose we have an array arr and want to give it a function as its first element. How can we do this?

Well, had the declaration syntax been so flexible then we could've just written the code below - but unfortunately it isn't.

var arr = [];

function arr[0]() {
    // block of code
}

This code throws an error due to a very obvious reason. Try to figure it out!

Why does the code shown above throw an error?
We're assigning a function to an array
The name of the function, following the function keyword, is invalid.
The function is empty

That's right - it's the name that cause the issue!

The identifier after the function keyword is supposed to be the function's name, with all the naming rules applied. Since arr[0] contains special characters [ ], the interpreter throws an exception on parsing it.

So clearly a function declaration won't suffice us in solving this simple problem. What we need instead is a function expression.

Consider the following code:

var arr = [];

arr[0] = function () {
    // block of code
}

Here we have the assignment syntax in action - a value is being assigned to arr[0] which turns out to be a function expression.

We say that arr[0] holds an anonymous function - a function without a name.

With the function successfully inside arr[0], we can now invoke it very easily using the same syntax we used before. Write the name of the identifer that holds the function and append it with a pair of parentheses.

// invoke the function saved in arr[0]
arr[0]();

Here arr[0] points to a function which then gets executed using the parentheses following.

And this is a function expression in real practical use. Just take an identifier and assign it a function! It's that simple!

Moving on, apart from the differences in creating named vs. anonymous functions using a declaration and an expression, there is yet another technical differences between these two ways.

Hoisting

Akin to variable declarations, function declarations are hoisted right at the top of their lexical scope - with value equal to the function itself.

A hoisted variable is equal to undefined, but a hoisted function is equal to the function itself.

This means that the following code is perfectly alright:

sayHello(); // call

// definition
function sayHello() {
    alert("Hello Programmer!");
}

The function sayHello() is called before it is actually declared (in line 4), but regardless doesn't cause an error. This is because the function is hoisted at the top of its scope, which in this case is the global scope, and is therefore available even before the location where it's actually declared.

In contrast to this, a function expression, assigned to a variable follows the hositing rules for variables, NOT functions!

This means that the code below will throw an error since this time sayHello, in its hoisted form, doesn't hold a function but rather the value undefined.

sayHello(); // call

// definition
var sayHello = function() {
    alert("Hello Programmer!");
}

sayHello is a variable here, and likewise will move up its scope with the value undefined. Invoking this value, in line 1, is the cause of the error, as undefined is not a valid function!

Therefore it turns out that both function declarations and function expressions have their own uses and applications. It's not a good vs. bad comparison but solely a purpose-oriented comparison.

To summarise it all:

Declarations are useful to create simple named functions while expressions are the way to go if functional values are to be assigned to any sort of identifiers, such as array elements, object properties and so on.

Anonymous Functions and IIFE's

All the functions we have created uptil now can be classified as named functions i.e they had names attached to them which could be used in invocation statements. The functions could easily be called multiple number of times since they had a name - an identity. With JavaScript you get one interesting form of functions known as anonymous functions.

As the name suggests these functions don't have names and therefore can't be called again and again. See the following example of an anonymous function.
function() {
    alert("Hello Programmer!");
} // a function with no name
This code won't through an error, in fact it even shouldn't, since the code is perfectly fine. It is just useless to write because the function can never be called "owing to the way it has been written". So is there any way of calling an anonymous function? Yes there is a way of calling an anonymous function as you can see here.

We call such functions IIFE's (Immediately Invoking Function Expressions) or self-invoking functions.
(function() {
    alert("Hello Programmer!");
})();
The pair of parentheses at the end of line 3 are responsible for the invocation of this anonymous function.

Beware of the enclosing parentheses

You might have noticed in the second code snippet that we have enclosed our function definition inside a pair of parentheses unlike in the first one and wondering why we did so.

The following code will throw an error since the interpreter doesn't recognise why is there a pair of parentheses ( ) after a pair of curly braces { }. This is syntactically invalid and the interpreter likewise throws an error.
function() {
    alert("Hello Programmer!");
}();
With parentheses enclosing the function definition, the interpreter executes the preceding expression which is our function definition (since it is syntactically valid). You can think of the enclosing parentheses as grouping the function definition which can then be invoked easily.
(function() {
    alert("Hello Programmer!");
})();

In conclusion

Functions are an integral part of dynamic web pages interacting with the user and this chapter is an integral part of functions so make sure you understand everything in it.