code

JavaScript Arrow Functions

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:

const myFunc = function() {
  const myVar = "value";
  return myVar;
}

ES6 provides us with the syntactic sugar to not have to write anonymous functions this way. Instead, you can use arrow function syntax:

const myFunc = () => {
  const myVar = "value";
  return myVar;
}

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 simplify smaller functions into one-line statements:

const myFunc = () => "value";

// You can write them like this when there are no parameters

const doubler = item => item * 2;

// with parameters do this

const multiplier = (item, multi) => item * multi;
multiplier(4, 2);

We can also have default values now

const greeting = (name = "Anonymous") => "Hello " + name;

console.log(greeting("John"));
console.log(greeting());

When you don’t know how many parameters a function will accept:

function howMany(...args) {
  return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2));
console.log(howMany("string", null, [1, 2, 3], { }));

The console would display the strings You have passed 3 arguments. and You have passed 4 arguments..

The rest parameter eliminates the need to check the args array and allows us to apply map()filter() and reduce() on the parameters array.

Leave a Reply

Matt is the author of five Apress books including Learn RStudio IDE, Quick, Effective, and Productive Data Science, Objective-C Recipes, Swift Quick Syntax Reference, Objective-C Quick Reference, and the upcoming Pro Data Visualization with R and JavaScript. He has over 20 years of experience in technology, psychometrics, and data analytics working in major higher education institutions such as The College Board and Educational Testing Service. He has earned a Master’s degree in Information Systems Management and a Bachelor’s degree in Quantitative Psychology.