DEV Community

SCDan0624
SCDan0624

Posted on

4 2

Javascript ES6: Arrow Functions

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay