loading...

Javascript ES6: Arrow Functions

scdan0624 profile image SCDan0624 ・1 min read

Arrow Functions

Sometimes when coding our projects in javascript we will create anonymous functions instead of named functions. We usually do this for functions we only plan on using once, such as when using a function as an argument.

Before ES6 we would code our anonymous functions like this:

const myFunc = function(){
  const myDog = "Penny";
  return `My dogs name is ${myDog}`
}

myFunc() // My dogs name is Penny

Enter fullscreen mode Exit fullscreen mode

ES6 provides us with arrow functions which allow us to write these anonymous functions in a with less code:

const myFunc = () => {
  const myDog = "Penny";
  return `My dogs name is ${myDog}`
}

myFunc() // My dogs name is Penny
Enter fullscreen mode Exit fullscreen mode

Even better if there is there is no function body and only a return value, arrow function syntax allows you to omit the return keyword and the brackets.

const myFunc = () =>  "My dogs name is Penny"
myFunc() // My dogs name is Penny

Enter fullscreen mode Exit fullscreen mode

Writing Arrow Functions With Parameters
Just as with regular functions you can pass arguments as parameters in arrow functions:

const addFive = (num) => num + 5
addFive(1) // 6
Enter fullscreen mode Exit fullscreen mode

If there is only one argument you can shorten the code even more by omitting the parentheses around the argument.

const addFive = num => num + 5
addFive(1) // 6
Enter fullscreen mode Exit fullscreen mode

You can also still pass multiple arguments into an arrow functions

const addNums = (num1,num2) => num1 + num2
addNums(10,5) // 15
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide