Function expressions

Function expressions are the easiest and most predictable to use as they are syntactically similar to all the other values within JavaScript. You can use them to literally define functions anywhere you would define any other value as they are a type of expression. Observe here, for example, how we're defining an array of functions:

const arrayOfFunctions = [
function(){},
function(){}
];

A common application of the function expression is in passing callbacks to other functions so that they can be called at some later point. Many native Array methods, such as forEach, accept functions in this manner:

[1, 2, 3].forEach(function(value) { 
// do something with each value
});

Here, we are passing a function expression to the forEach method. We haven't named this function by assigning it to a variable, so it is considered an anonymous function. Anonymous functions are useful as they mean that we don't need to preassign a function to a variable in order to make use of it; we can simply write our function into our code at the exact location of usage.

The function expression is most similar in its expressive manner to the arrow function. The key difference, as we will discover, is that the arrow function does not have access to its own bindings (for example, to this or arguments). A function expression, however, does have access to these values, and so in some contexts will be more useful to you. It's very common to need a binding to this in order to operate successfully with the DOM API, for example, where many native DOM methods will invoke callbacks and event handlers with the relevant element as execution context. Additionally, you'll want to use function expressions when defining methods on objects or prototypes that will need to access the current instance. As illustrated here, using an arrow function would not be appropriate:

class FooBear {
name = 'Foo Bear';
}

FooBear.prototype.sayHello = () => `Hello I am ${this.name}`;
new FooBear().sayHello(); // => "Hello I am ";

FooBear.prototype.sayHello = function() {
return `Hello I am ${this.name}`;
};
new FooBear().sayHello(); // => "Hello I am Foo Bear";

As you can see, using the arrow function syntax prevents us from accessing the instance via this, while the function expression syntax allows us to do this. Therefore, the function expression, although somewhat superseded by the more succinct arrow function, is still a very useful tool.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.70.255