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
}
After Arrow function
const greet = (name)=>{return "hello" +name}
const greet = name=> "hello" + name
Syntax break down
const functionName = (parameters) => {
// code
};
`- 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
Arrow function
const User = {
name:"Tony",
greet: ()=>{
return this.name
}
}
user.greet()
// returns undefined
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)