Function Expressions vs Declarations

I’ll start my first blog post with a basic concept that all new Javascripters will face: understanding the difference between function expressions and function declarations.

While a relatively simple concept, it’s important that those learning the language master this early on. In general, a function is a bit of code that can be called later on to perform pre-programmed tasks. It can take in values called parameters — such as strings, numbers, other functions, etc. — do things to these inputs, and return another value, or output.

There are two ways in which a function can be defined: expressions and declarations. Function expressions typically define functions with assignment to a variable.

var myFunc = function(num) {
return num + 3;
};

Now if I wanted to call this function with a parameter of “7” to receive an output of “10”, I could invoke the function by using myFunc(7);. All function expressions never begin with the word “function” (even self-invoking functions start with an open parenthesis before the word “function”).

On the other hand, function declarations do begin with the word “function”. For example:

function foo(num) {
return num + 3;
}

Function declarations define functions without the need to assign them to variables.

Both of these methods essentially do the same thing, so you may be asking:When should I write a function expression over a function declaration, and vice versa?

Function declarations, like the var keyword, are hoisted to the top of other code. Function expressions aren’t, so this helps with closures and maintaining local variable scope. Function expressions often result in cleaner, easier to read code.