JavaScript Functions

Typically Javascript functions are defined as follows:

function theFunctionName(paramOne, paramTwo) {
	return paramOne + ' ' + paramTwo;

Arrow Functions

However, you can also use arrow functions to define functions in Javascript. Arrow functions were introduced to Javascript in ES6. A simple arrow function version of the above function looks like this:

const theFunctionName = (paramOne, paramTwo) => {
	return paramOne + ' ' + paramTwo;

Arrow functions are anonymous functions and they must always be assigned to a variable.

Defining arguments in arrow functions

When defining multiple arguments in an arrow function, they should be wrapped in brackets. However, if you’re defining a single argument, there is no need for the brackets. Take a look at this example:

const theFunctionName = param => {
	return param;

There is no need to wrap param in brackets.

Implicit return in arrow functions

With arrow functions, you can remove the parentheses and the function will return the result.

const theFunctionName = (paramOne, paramTwo) => paramOne + ' ' + paramTwo;

Always remember, when removing the parentheses to remove the return keyword. The function will not work with the return keyword. Also, only use the arrow function without the parentheses if you want a value returned.

This works best with functions that have a single expression. Having more than one expression would need to be wrapped in parentheses.

Implicit return of objects in arrow functions

Perhaps you want to return an object using the shorthand implicit return. Take a look at this for example:

const theFunctionName = param => {name: “Matt”}

This will result in an error. The reason for this is because Javascript doesn’t know whether the first parentheses is the start of an object or an opening of a function definition. To get around this, we can wrap the contents of the function in brackets like this:

const theFunctionName = (param) => ({name: “Matt”})

How arrow functions handle this

With arrow functions this is determined by the this of the outer scope of the function. Arrow functions don’t have their own this context as there is no binding of this.

Have a look at the following two examples to further explain this:

function handleClick() {
	// Value of `this` is the button that was clicked.

let clickEvent = document.getElementById("button").addEventListener("click", handleClick);
let handleClick = () => {
	// Value of `this` is the outer context of the function definition, thus the `window` object.

let clickEvent = document.getElementById("button").addEventListener("click", handleClick);

Further learning

When to use arrow functions vs standard functions

Web Dev Simplified


Leave a Reply

Your email address will not be published. Required fields are marked *