Articles by Victoria

A Simple Guide to Arrow Functions in JavaScript

Jul 24, 20201 min read
cover

If you are learning JavaScript, it is inevitable that you will hear about "arrows". Let's learn about arrow functions!

What is an Arrow Function?

Arrow functions use the arrow syntax to accept arguments and run in their enclosing scope context.

Syntax

// Function that returns a single expression
(param1, param2) => return_expression

// Function with code block
(param1, param2) => {
statements
return some_expression
}

Example

// Regular function
const add = function (a, b){
return a+b;
}

// Arrow function
const add = (a,b) => a + b

When to use them

1. Functions that iterate


Arrow functions work great with map(), filter(), reduce().

2. Promise chains


Arrow functions make promise chains cleaner and more concise.

3. Callback Functions


Reduce callback function code significantly.

When NOT to use

1. Constructors


Arrow functions don't have their own 'this'.

2. Object Methods


Arrow functions bind to window scope, not object scope.

3. Callback Functions with 'this'


When you need 'this' to refer to the element.

Conclusion

Arrow functions are revolutionary but come with limitations. Thanks for reading!

Share:

More Articles