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:
const greeting = function(name) {console.log("hello " + name);}
The new syntax with a fat arrow looks like this:
var greeting = (name) => {console.log(`hello ${name}`);}
We can go further if we only have one parameter. We can drop the parentheses and write:
var greeting = name => {console.log(`hello ${name}`);}
If we have no parameters at all, we need to write empty parenthesis like this:
var greeting = () => {console.log(`hello ${name}`);}
const greeting = name => `hello ${name}`;
Look at a side by side comparison with an old ES5 Function:
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