DEV Community

loading...
Cover image for Arrow Functions in JavaScript

Arrow Functions in JavaScript

hebashakeel profile image hebaShakeel ・2 min read

A function is a block of code, self contained, that can be defined once and run any number of times you want. It can optionally accept parameters, and returns one value.
In addition, functions are said to be first class functions because they can be assigned to a value, and they can be passed as arguments and used as a return value.

pre-ES6 syntax of function declaration:

Alt Text

Arrow Functions were introduced in the ES6/ES2015 and are very widely used. It allows us to write functions with a shorter functions. They are particularly nice to use when working with inline functions, as parameters or callbacks.
They cannot be used as constructors. When instantiating an object, they will generate a TypeError.

Alt Text

EXAMPLES:

Alt Text

Alt Text

Alt Text

Arrow functions allow you to have an implicit return, i.e. you can return values without using the keyword return.

Benefits of using arrow functions

1.They make the ' this ' keyword more manageable.

2.They are easier to read and write.

3.We do not need to worry about call, apply, bind and new. They have no effect on arrow functions.

In a normal function, the ' this ' keyword may be bound to different values based upon the context in which the function was called.
Arrow functions use their lexical scope for this.

Lexical ' this '

Arrow functions do not have their own ‘ this ’. That’s why they use the ‘ this ’ value of the scope they are enclosed in. This is very useful for Object-Oriented style of programming in JavaScript.

Normal function using ' this ':

Alt Text

Arrow function using ' this ':

Alt Text

Unlike regular functions, arrow functions do not have their own this. The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

I hope you found this article helpful. Don’t forget to post your queries, doubts in the comment section below. I will be more than glad to help!

Thank You!

Discussion (0)

Forem Open with the Forem app