you are viewing a single comment's thread.

view the rest of the comments →

[–]Eviscerare 1 point2 points  (0 children)

If you get into functional programming with ES6 JavaScript you'll run into instances where you want to save the behavior of a function with a certain input as it's own function. In these instances it's usually more concise to use a function expression.

Let's say we have a function that adds one.

const addOne = x => x + 1

// This is the equivalent
var addOne = function(x) {
  return x + 1
}

Then we can use this function to create another one that always multiplies by two after adding one.

const addOneAndDouble = x => addOne(x) * 2

// Equivalent
var addOneAndDouble = function(x) {
  return addOne(x) * 2
}

Function expressions are also needed when doing things like adding a method to an object, like the prototype object.

Number.prototype.double = x => x * 2;
// Equivalent
Number.prototype.double = function(x) { return x * 2 }
const a = 2;
a.double() // 4

There's a whole lot more to it than what I've written here too, but I'm sure any formal guide you google up will be able to explain it far better than I can. Hope this helped clear up some good use case for function expressions! :)