DEV Community

Randy Rivera
Randy Rivera

Posted on

ES6: Use Arrow Functions to Write Concise Anonymous Functions

In JavaScript, we often don't need to name our functions, especially when passing a function as an argument to another function. Instead, we create inline functions. We don't need to name these functions because we do not reuse them anywhere else.

  • To achieve this, we often use the following syntax:
var magic = function() {
  return new Date();
};
Enter fullscreen mode Exit fullscreen mode

ES6 provides us with the syntactic sugar to not have to write anonymous functions this way. Instead, you can use arrow function syntax, When there is no function body, and only a return value, arrow function syntax allows you to omit the keyword return as well as the brackets surrounding the code. This helps just to make smaller functions into one-line statements:

const magic = () => new Date();

console.log(magic()); will display 
Sun Apr 25 2021 17:56:27 GMT-0400 (Eastern Daylight Time)
Enter fullscreen mode Exit fullscreen mode

At least from the date I'm writing this code.

Top comments (0)