Ways to Declare JavaScript Functions

The different ways to declare a function in JavaScript

To var, or not to var

You can declare a function as you would any other JavaScript variable:

With var
1
2
var func1 = function () {
};

Or you can declare it without a var in your statement:

Without var
1
2
function func2() {
}

The difference

I recently read an accepted answer on Stack Overflow that stated:

If you’re in the global scope then there’s no difference.

- Stack Overflow

I’m sorry but I don’t agree. If that statement was correct, then I would get the same result for this:

Same result?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
try {
func1();
} catch (ex) {
alert(ex);
}
var func1 = function () {
alert("func1 success");
};
try {
func2();
} catch (ex) {
alert(ex);
}
function func2() {
alert("func2 success");
}

As you can see, attempting to call func1 before it has been declared throws an error, whereas func2 is able to be called successfully. This means that there is a difference and it’s nothing to do with scoping, either locally or globally:

  • func1 (var format) is defined at runtime
  • func2 is defined before runtime, they’re “hoisted

Function expressions

I refer to the first (with var) declaration as a function expression. func1 is actually an anonymous function expression, the variable that is assigned the function has a name, func1 but the function itself doesn’t. To give the function itself a name, you could do:

Named function expression
1
2
var func1 = function funcName() {
};

Best practice

Function expressions are more versatile, if you create a new function with currying or Multiple Function Composition you’re using a function expression. Function expressions go hand in hand with functional programming. Personally, I always define my functions as an expression (the first way, using a var), therefore it must be best practice :)

CoffeeScript fans

If you’re a CoffeeScripter, get off my blog ;). Also, there’s only one way you can define a function in coffeescript:

Coffeescript
1
func = ->

Which is evaluated as a function expression, fortunately.

Now seriously, get off my blog CoffeeScripters.