Function Expressions

Contact Us or call 1-877-932-8228
Function Expressions

Function Expressions

Another way to define a function is with a function expression:

var foo = function(bar) {
	return bar + 3;
}

which we could then call in exactly the same manner as with our function declaration example above:

document.write(foo(9));

Unlike declared functions, function expressions are not hoisted: they are created when the execution flow reaches them. As such, function expressions can be used only after they are defined.

As we'll see later in this lesson, function expressions are useful for closures, as arguments to other functions, and as immediately invoked function expressions (IIFEs). More on this to come.

Let's look at a quick example of the difference between function declarations and function expressions:

Code Sample:

AdvancedFunctions/Demos/functionDeclarationExpression.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Function Declarations &amp; Expressions</title>
</head>
<body>
	<h1>Function Declarations &amp; Expressions</h1>
	<script>
		document.write(funDeclaration(10) + ' ');
		function funDeclaration(x) {
			return x + 17;
		}
		document.write(funDeclaration(2));

		document.write('<hr>');
		
		//document.write(funExpression(3) + ' ');
		var funExpression = function(y) {
			return y * y;
		}
		document.write(funExpression(9));
	</script>
</body>
</html>

Code Explanation

Function funDeclaration is a declared function; note that we can call it before or after it is defined, since declared functions are hoisted.

Function funExpression is a function expression. If we were to uncomment the call document.write(funExpression(3) + ' '), which comes before we define function funExpression, we would get an error because function expressions are not hoisted.

Next