JavaScript: Arrow Functions

Beginner’s guide to understanding and writing Arrow Functions

Jackson Chen
2 min readAug 12, 2020

Whether you are starting your programming journey in a coding bootcamp or dabbling into JavaScript for the first time, encountering the Arrow Function can be quite daunting and confusing.

In fact, learning how to use Arrow Functions can be a powerful tool to have under your belt when used properly.

By this time, you are probably familiar with the classic function declaration method function foo() {...} as seen below:

function greet(name) {
return `Hello ${name}.`
}
greet('Joe')// "Hello Joe."

Or as a function expression let foo = function() {...}

let greet = function(name) {
return `Hello ${name}.`
}
greet('Joe')// "Hello Joe."

Although still effective, writing our functions this way can be quite repetitious and bulky at times. What if we were able to condense our code?

Want to read this story later? Save it in Journal.

That’s where Arrow Functions come in. let foo = () => {...}

let greet = (name) => {return `Hello ${name}.`}greet('Joe')// "Hello Joe."

We are able to further condense our Arrow Function given certain limitations.

If your Arrow Function :

  • only has one parameter, you are allowed to omit the parenthesis () from the parameter.
  • expression is only one-line in length, you can omit the curly brackets {} and the return from the expression. This is known as implicit return.
let greet = name => `Hello ${name}.`greet('Joe')// "Hello Joe."

Pretty awesome right? More commonly, you will probably encounter them when using iterators such as .map or .forEach. Here you can see an example of using function declaration vs the Arrow Function as a callback function for .map.

Function Declaration

let numbers = [1, 2, 3]numbers.map(function(number) {
return number * 2
}
)
// [2, 4, 6]

Arrow Function

let numbers = [1, 2, 3]numbers.map(number => number * 2)// [2, 4, 6]

Arrow Functions makes it easier for us to write short-hand code which can increase in code readability, open to less bug opportunities and often used in more advanced libraries such as React. Of course there will be times when using the function declaration method is preferred. Ultimately, it is up to you as the programmer to decide which method is better suited for the task.

Thanks for reading and happy coding!

Resources

📝 Save this story in Journal.

--

--

Jackson Chen

Pre-med turned software engineer. Writing about my experiences and what I’ve learned. Let’s connect. https://jacksonchen.dev