Function Declarations vs Expressions: A Quick Guide

Here's the question: What's the difference between these two methods of creating a function?

function a() {
	//This is known as a function declaration
	console.log("Hello");
}

var b = function() {
	//This is known as a function expression
	console.log("World");
}

Both of these methods do almost the same thing, however there is one major difference:

a(); // "Hello, World"
b(); // Error

function a() {
	console.log("Hello, World");
}

var b = function() {
	console.log("Hello, World");
}

Unlike Function Expressions, which behave much in the same way that any other variable assignment would, Function Declarations are affected by a JavaScript feature called hoisting.

Hoisting is where JavaScript moves function and variable declarations to the top of their scope. This is so that developers can freely choose how they want to organise their code without worrying about where a function has been declared.

Which one do I use?

Since both approaches are largely the same, it's less important which approach you use, and more important that you are consistent.

Personally, I prefer to use function declarations at the top level, and function expressions for any inner functions, like so:

function foo() {
	var bar = function() {
		console.log("Hello, World");
	}

	setTimeout(bar, 1000);
}

The only exception is that that due to hoisting, function declarations behave the same as var, so you need to use let a = function() {} to get functions to use block scoping (or const).

If you want to read some more about functions in JavaScript, you can check out my guide to closures.

Can't get past JavaScript Tutorials?

Download my FREE ebook on how to succeed as a self-taught JavaScript Developer, and how to find projects that you'll actually finish. Learn More...