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
});