Javascript
JavaScript Fundamentals -- Functions in JavaScript

Arrow Functions

PRO
Outline

Another type of function in JavaScript is the arrow function (or lambda function). Arrow functions are especially great when being used as a callback, but you don’t only have to use them as callbacks. They’re quick and concise to write, which is why they're so popular. One thing to remember though is that they have a different context than a named or anonymous function. You can read about that here or go back to the video in this course on function scope.

Here are a couple examples of arrow functions:

const sayHi = () => console.log('Hello there!');

const arr = ['Item 1', 'Item 2'];
arr.forEach((item) => console.log(item)); // Item 1 Item 2
// or
arr.forEach((item) => {
  console.log(item); // Item 1 Item 2
}

The first two examples above are one line arrow functions. It's also referred to as implicit return. It's an implicit return because there is no return keyword used. You'l also notice that there's no body surrounded by curly brackets for the function. All that you have is the room between the arrow and the semicolon to put the body of your function. This usually means that what you're doing should be quick and to the point. If you have any logic, you should use curly brackets for the body of the function.

Some callback functions, like the sort function on an array, for example, require you to return something from the callback function. If you don't use the implicit return syntax and instead use curly brackets, make sure the function you provide uses the return keyword.

If your arrow function is returning an object, you should either use curly brackets and have a body to the function with the return keyword that returns an object OR wrap your returned object in parentheses in a one line arrow function:

const dogs = ['Max', 'Duke'];
const dogsObjects1 = dogs.map((dog) => ({ name: dog }));
console.log(dogsObjects1); // [{ name: 'Max' }, { name: 'Duke' }]
// OR
const dogsObjects2 = dogs.map((dog) => { 
  return { name: dog };
});
console.log(dogsObjects1); // [{ name: 'Max' }, { name: 'Duke' }]

The result is the same in both situations, but if you don't wrap the object in parentheses like I did in the first example your arrow function won't work as you expect.

You can learn more about arrow functions in this blog post.

 

I finished! On to the next chapter