Introduction to Arrow Functions

Arrow functions are a new syntax for defining functions in JavaScript. They provide a concise and more readable way to write functions, especially when dealing with functions that are passed as arguments to other functions or when creating simple one-liner functions.

The syntax for an arrow function uses the => symbol, hence the name arrow. Here's an example of a traditional function and its equivalent arrow function.

Arrow Functions with multiple lines and multiple parameters

If we have multiple lines in the function body, we need to wrap the function body in curly braces and use the return keyword. And if we have multiple parameters, we need to wrap them in parentheses.

Loading Code . . .

Ok, not so different from the traditional function. But let's see how we can simplify the arrow function.

Arrow Functions with a single parameter

If we have a single parameter, we can omit the parentheses around the parameter in the arrow function:

Loading Code . . .

Arrow Functions with a single line

If we have a single line in the function body, we can omit the curly braces and the return keyword in the arrow function:

Loading Code . . .

As you can see, the arrow function is much shorter and more concise.

There are more differences between arrow functions and traditional functions, but we'll cover them in the more advanced sections. For now, let's focus on the syntax.


Code Time!

Now it's your turn to practice writing arrow functions. In the editor, you'll find a function called triple. Rewrite the function using an arrow function.

Loading...

© 2024 - ®Mewters