Arrow functions
Arrow functions are just unnamed or anonymous functions. The general syntax of arrow functions is shown in the following expression:
( args ) => { // function body }
Arrow functions provide a means of creating concise callable functions. By this, we mean arrow functions are not constructible, that is, they can't be instantiated with the new keyword.
The following are different ways of how and when to use arrow functions:
- The arrow function can be assigned to a variable:
const unnamed = (x) => { console.log(x) } unnamed(10) //Â Â 10
- Arrow functions can be used as an IIFE (Immediately Invoked Function Expression). IIFEs are functions that once encountered by the JavaScript compiler are called immediately:
((x) => { Â Â Â Â console.log(x) })("unnamed function as IIFE") // output: unnamed function as IIFE
- Arrow functions can be used as callbacks:
function processed(arg, callback) { Â Â Â Â let x = arg * 2; Â Â Â Â return callback(x); } processed(2, (x) => { Â Â Â Â console.log(x + 2) });Â Â Â // output:Â Â 6
While arrow functions are great in some situations, there is a downside to using them. For example, arrow functions do not have their own this
scope, hence its scope is always bound to the general scope, thereby changing our whole idea of function invocation.
In the Understanding the this property section, we talked about how functions are bounded to their invocation scope and using this ability to support closure, but using the arrow function denies us this feature by default:
const Obj = { Â Â Â Â Â name: "just an object", Â Â Â Â Â func: function(){ Â Â Â Â Â Â Â Â Â Â console.log(this.name); Â Â Â Â Â } } Obj.func() // just an object
Even though in the object, as shown in the code snippet, we make use of the anonymous function (but not the arrow function), we have access to the object's Obj
properties:
const Obj = { Â Â Â Â Â name: "just an object", Â Â Â Â Â func:Â Â () => { Â Â Â Â Â Â Â Â Â Â console.log(this.name); Â Â Â Â Â } } Obj.func() // undefined
The arrow function used makes the Obj.func
output undefined
. Let's see how it works if we have a variable called name
in the global scope:
let name = "in the global scope" const Obj = { Â Â Â Â Â name: "just an object", Â Â Â Â Â func:Â Â () => { Â Â Â Â Â Â Â Â Â Â console.log(this.name); Â Â Â Â Â } } Obj.func() // in the global
As we can see, Obj.func
makes a call to the variable in the global scope. Hence, we must know when and where to use the arrow functions.
In the next section, we will talk about Promises and async/await concepts. This will give us the power to easily manage long-running tasks and avoid callback hell (callbacks having callbacks).