JavaScript Arrow Functions

Introduction

Functions are a collection of instructions that are used to accomplish a task. In JavaScript, there are two types of functions you’ll see often; the standard function and the arrow function. Now, there are some key characteristics that separate arrow functions from the standard function. But first, let’s discuss the standard function briefly.

 

Standard Functions

Standard function in JavaScript has interesting properties. They can be instantiated; this means they can be created with the new keyword. Now, that could be bad because it may be unintended behavior in your program; you want your functions to be functions, not objects. Now, these functions are also hoisted. What’s hoisted? It means that the function is always brought to the top of the current scope; it’s available before it’s defined in your program. Now, this is a good feature but can be messy; use it with caution. And to illustrate the power of these functions here’s an example showcasing their characteristics.

As you can see the function is hoisted and can be called earlier in the program. Also, the function can be called with the new keyword, because functions are objects. Now, these characteristics are different compared to arrow functions. So, let’s discuss the awesome arrow functions.

 

Arrow Functions

Arrow functions are specialized, giving them different characteristics from standard functions. Unlike standard functions, they are not hoisted and can’t be instantiated (called with the new keyword). Lastly, they are lexically scoped. This is a defining factor so let’s explain lexical scoping.

Lexical scoping means that the functions do not create a new function scope when defined. Now, the scope defines where variables exist. The scope is simply a block scope and will not change the context of “this”. Now, “this” refers to the current function or object you’re in at the time.; if you use a standard function, “this” will refer to the new standard function. As a result, arrow functions are often the best choice for anonymous functions or for writing functions that are very explicit. Here’s an example showcasing all their characteristics.

As you can see, they are very beneficial shortening the amount of code you have to write significantly. Also, they maintain the context correctly; an important feature which allows for the writing of callback functions that are smaller more performant. As you can see, it also throws an error if you try to instantiate an arrow function, which allows you to keep unintended side effects out of your program.

 

Conclusion

Personally, I believe arrow functions are a great addition to the JavaScript language. Understanding and using them effectively will improve your code,  and shorten all that code you have to write. Now, I hope you learned something and keep on improving.

 

Leave a Reply

Your email address will not be published.