The function
keyword is typically used to declare functions.
In ES6, a new syntax for writing functions with a clearer and more readable structure was introduced which is called arrow functions
. With this syntax You can write the same function in a shorter format by using arrow functions.
Let's look at an example.
This is the traditional way of declaring a function with the function
keyword.
function Multiply(a, b) {
return a *b;
}
console.log(Multiply(2,3));//6
Let's take the same example but use an arrow function
const multiply = (a,b) => {
return a *b;
}
console.log(multiply(2, 3)); //6
The above function can be shortened. We can remove the brackets and the return
keyword if the function only has one statement and the statement returns a value like so:
const multiply = (a,b) => a*b;
console.log(multiply(2, 3)); //6
We've previously seen arrow functions
in the JavaScript Tutorial Series: Higher order functions lesson.
Using arrow functions as callback functions is a great idea due to their clear syntax, implicit return. They can make your code simpler to read and understandable, and lessen the likelihood of bugs and errors.
Top comments (0)