DEV Community

Sujith V S
Sujith V S

Posted on • Updated on

Arrow Function | JavaScript ES6.

Let's take a look at the normal js function.

function myName(name){
    console.log(name);
}
myName("Sujith")
Enter fullscreen mode Exit fullscreen mode

The above function can be written in arrow function as,

const myName = (name) => {
    console.log(name)
}
myName("Sujith")
Enter fullscreen mode Exit fullscreen mode

In arrow function we assign the function body to a variable, and we pass the arguments through the parenthesis between = and =>
eg:= (name) =>
And the body of the arrow function comes in between the curly braces {}.We can use return keyword to return a value in the function.

Arrow function with one argument.

const myName = name => {
    console.log(name)
}
myName("Sujith")
Enter fullscreen mode Exit fullscreen mode

If an arrow function is having only one argument, then we can exclude the parenthesis while passing the argument.= name =>

Arrow function with single statement.

const myNumber = nbr => nbr * 5

console.log(myNumber(5))
Enter fullscreen mode Exit fullscreen mode

If an arrow function has only a single statement to return or execute, then we can exclue the {} and write them as => nbr * 5. It automatically returns that statement after => and we don't need to use return keyword.

Top comments (0)