Arrow Functions

This lesson covers the new way of declaring functions introduced in ES6.

What is an arrow function? #

ES6 introduced fat arrows (=>) as a way to declare functions. This is how we would normally declare a function in ES5:

Press + to interact
const greeting = function(name) {
console.log("hello " + name);
}

The new syntax with a fat arrow looks like this:

Press + to interact
var greeting = (name) => {
console.log(`hello ${name}`);
}

We can go further if we only have one parameter. We can drop the parentheses and write:

Press + to interact
var greeting = name => {
console.log(`hello ${name}`);
}

If we have no parameters at all, we need to write empty parenthesis like this:

Press + to interact
var greeting = () => {
console.log(`hello ${name}`);
}

 

Implicitly return #

With arrow functions, we can skip the explicit return and return like this:

Press + to interact
const greeting = name => `hello ${name}`;

Look at a side by side comparison with an old ES5 Function:

Press + to interact
const oldFunction = function(name){
return `hello ${name}`
}
const arrowFunction = name => `hello ${name}`;

Both functions achieve the same result, but the new syntax allows you to be more concise. Beware! Readability is more important than conciseness so you might want to write your function like this if you are working in a team and not everybody is ...

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy