JavaScript Arrow Functions Explained

JavaScript arrow functions, or lambdas, are a way to reduce the lines of code around writing functions. This can make code more readable if used in an appropriate way. When using arrow functions you can remove a few lines of code and make your code a bit more succinct and readable.

The below code snippet shows a basic function and then calling that function. This code will simply print the string value “Hello World” to the console. If you don’t understand this example please read this post where I explain the basics of functions first – Functions in JavaScript (https://acroynon.com/functions-in-javascript/)

The below code snippet will achieve the exact same thing. We create a variable called ‘hello’ and assign it the value of a function. When we then call this function it will print the string value “Hello World” to the console. This is an example of an arrow function, as you can see it’s basically just a quick way of writing a function (as you don’t have to write the ‘function’ keyword).

The previous example showed a single line function if you want to write a larger function you have to surround it with curly brackets {..}. This is similar to a normal function declaration. You can also return values, so now our ‘hello’ variable will be equal to the string value “Hello World” instead of being equal to a function.

The below javascript code shows a function called ‘split’ that takes a single parameter and returns an array based on splitting the input string on commas. So the below ‘result’ will contain an array with three elements, the letters a – c.

This code will achieve the exact same as the above example, but we are using an arrow function to achieve it this time. You can see how the parameter now goes within the brackets of the arrow function, similarly to a normal function declaration.

We can also use arrow functions for more complicated examples, such as the filter function. The below code shows using the filter function on an array of numbers to only return numbers above the number 2. This will return a list of numbers 3 – 5. The inner function passed into the filter function will be applied to each element of the array and will either add or not add the element to the result dependent on a boolean response.

We can simplify the code above by using an arrow function, as shown below. This is a bit easier to read then the above example as we are able to remove the ‘function’ keyword and few of the brackets. However, just because you can use arrow functions doesn’t mean all functions have to be arrow functions, as sometimes it can make code less readable.

Leave a Reply