DEV Community

Hiral
Hiral

Posted on

Arrow Functions in JavaScript: A Simpler Way to Write Functions

Arrow function allow shorter syntax to write function in JavaScript
They were introduced in ES6 to improve code readability
Before arrow function:

function greet(name){
return "hello" + name
}
Enter fullscreen mode Exit fullscreen mode

After Arrow function

const greet = (name)=>{return  "hello" +name}
const greet = name=> "hello" + name

Enter fullscreen mode Exit fullscreen mode

Syntax break down

const functionName = (parameters) => {
   // code
};
Enter fullscreen mode Exit fullscreen mode

`- const → usually used to define arrow functions

  • (parameters) → inputs
  • => → arrow symbol
  • {} → function body`

Arrow function with one parameter

const greet = name => "hello" + name

if the function has only one statement that returns a value.You can remove the brackets and return value

Arrow function with mutltiple parameter
const greet = (firstname, lastname) => "hello" + firstname + lastname

Arrow function with multiple parameter and multiple statement
const greet = (firstname, lastname) => {
let name = firstname + lastname
return "hello" + name
}

with mutliple statement it is important to have bracket and return statement

Arrow function this keyword
Normal function

const User = {
  name:"Tony",
  greet: function(){
   return this.name
  }
}
user.greet()
// returns Tony
Enter fullscreen mode Exit fullscreen mode

Arrow function

const User = {
  name:"Tony",
  greet: ()=>{
   return this.name
  }
}
user.greet()
// returns undefined
Enter fullscreen mode Exit fullscreen mode

Some important points about arrow function:

  • It must be declared before use
  • Arrow function does have this keyword they inherit from surrounding area

Top comments (0)