Ender Ender - 8 months ago 29
Javascript Question

What is the point of using a function expression over a function statement in Javascript?

I understand that a expression wont "exist" until it is reached by the execution context. I'm just wondering is there any area where the use of a function expression would be better than a normal function statement where you don't have to worry about when the function will be saved to memory.

I'm fully aware of how they work as in differences i'm just curious as to the uses for expression.


Function expressions are useful in several circumstances:

When assigning a function to a property:

SomeClass.prototype.myMethod = function(args) {
    // implementation

When creating a variable that may contain a different implementation based on circumstances:

var sortFn;

if (high > low) {
    sortFn = function(...) {
        // sort increasing order
} else {
    sortFn = function(...) {
        // sort decreasing order

// some code that uses sortFn()