Ender
Ender

Reputation: 11

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.

Upvotes: 0

Views: 214

Answers (2)

jfriend00
jfriend00

Reputation: 708056

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()

In an IIFE (immediately invoked function expression):

var getUniqueID = (function() {
   var counter = 0;
   return function() {
       return counter++;
   }
})();

console.log(getUniqueID());   // 0
console.log(getUniqueID());   // 1
console.log(getUniqueID());   // 2

There are many other references on the usefulness of an IIFE:

Javascript why wrap a variable or constructor in an IIFE?

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

What is the (function() { } )() construct in JavaScript?

What is the purpose of a self executing function in javascript?

Advanced Javascript: Why is this function wrapped in parentheses?

Inline function expressions for passing a function as an argument:

fetch(someURL).then(function(value) {
    // this is inside a function expression
}).catch(function(err) {
    // handle errors here
});

myArray.forEach(function(item, index) {
    // process each item of the array here
    // in this function expression
});

Upvotes: 5

john_mc
john_mc

Reputation: 1376

One such application might be when defining a callback function that you won't need a reference to after the callback has been executed. For example, if you're using an array method (such as map or reduce) with a very simple callback function, you may not feel the need to use a declaration.

var incrementValues = [1, 2, 3, 4, 5].map(function(val) {return val+1});

/// ===> incrementValues = [2, 3, 4, 5, 6]

Upvotes: 2

Related Questions