JavaScript Arrow functions were introduced in ES6. The main advantage is, it has shorter syntax. Let’s take a look.
Normal function:
function doSomething() { // your logic }
Arrow function
const doSomething = () => { // your logic }
Here no need to write the function
keyword to create a function. If you have only one line of code, then you can omit the braces and write the code in single line.
const doSomething = () => console.log('I am an Arraow function');
If you have only return
statement, then you can write it in single line without the return
keyword.
const doSomething = () => { return 'Hello, I am arrow function'; }
Above code can be written as:
const doSomething = () => 'Hello, I am arrow function'; console.log(doSomething()); // Hello, I am arrow function
This function syntax only works if you have only one statement.
Passing Arguments:
const add = num => { const a = 5; return num + a; } //OR const add = num => num + 5;
If your function has only one parameter, then you can write the parameter without parentheses but if parameters are more than one then parentheses are must.
const add = (num1, num2) => num1 + num2; console.log(add(4, 6)); // 10
The “this” keyword in Arrow function
In normal function this
refers to the object that calls the function, but in arrow function this
refers to the owner object. Let’s analyse in deep.
Try the below code and check the console to mark the difference.
function doSomething() { setTimeout(function() { console.log(this); // prints the global Window object }, 1000); } const obj = new doSomething();
Inside the setTimeout
function this
refers to the Window object. Now let’s see if you will write arrow function inside setTimeout
what it will refer as this
.
function doSomething() { setTimeout(() => { console.log(this); // prints doSomething object }, 1000); } const obj = new doSomething();
Well if you will write arrow function inside setTimeout
, this
inside setTimeout
refers to the owner object i.e. doSomething
.
Let’s see another example. Add a variable in the doSomething
function and increment by one in setTimeout
.
function doSomething() { this.num = 0; setTimeout(function() { console.log(++this.num); }, 1000); } const obj = new doSomething(); // prints NaN after 1 sec
Here in setTimeout
as this
refers to Window object, this.num
refers to the num
variable created in Window object. So by incrementing it, it gives NaN
as num
of Window was undefined earlier and ++undefined is NaN
. If you will do console.log(window.num)
you can see the variable num
present in window object.
console.log(window.num); // NaN
Now start using arrow functions whenever you write a new function.
Web Developer by Profession, Blogger by Passion.
JavaScript | React | Next | Angular | Vue | HTML | CSS