Arrow Functions vs Regular Functions*

image

There are two types of functions in JavaScript: regular functions and arrow functions. Arrow functions were introduced in ES6, and they are a more concise way of writing function expressions. In this blog post, we will discuss the differences between these two types of functions and when they should be used.

Regular Functions

Regular functions are declared with the function keyword, and they can be either function expressions or function declarations. Arrow functions are always function expressions.

Function declarations are hoisted, which means that you can call them before they are defined in your code. Function expressions, so you cannot call them before they are defined. See the example of a function expression below.

const getRectArea = function(width, height) {
	return width * height;
};

Arrow Functions

Arrow functions do not have their own "this" keyword. This means that they inherit the "this" keyword from the parent scope. Regular functions have their own "this" keyword, so they can create their own scope. They also cannot be used as constructors.

Arrow functions do not have a prototype property. Regular functions do have a prototype property.

When you shouldn’t use arrow functions

Object Methods

You shouldn't use arrow functions in object methods. this is not bound to anything meaning the values will not change because it inherits the value from the parent scope.

Dynamic Callback Functions

var text = document.getElementById('h1');
h1.addEventListener('hover, () => {
  this.classList.add('highlight');
});

Similar to the reason for object methods, usage of the keyword this wont mean anything, unless you like it there for looks 😀.

Conclusion

In most cases when the context isn’t bound to the function, arrow functions work fantastic. You can still use regular functions but it is much shorter and cleaner to write arrow functions especially as more businesses and applications are going down this path as well.

Hope this clears things up! If you have React and programming topics you’d like for me to cover, email me at christopher.clemmons2020@gmail.com.

Want to start a project with me? Send a inquiry to hello@digyt.co or visit digyt.co/contact