Arrow Functions

Learn Arrow Functions in ES6

You don’t need to have kept up with every ES6 change to know about Arrow functions, they’ve been the source of much talk and some confusion (at least initially) to JavaScript developers. I just want to point out how arrow functions provide a method for condensed code for simple functions:

// Adds a 10% tax to total

Normal Function Declaration –

function calculateTotal (total){
return total * 1.1;
console.log(calculateTotal(10)); //11

and you get the result.

Now, if i write the same function in Arrow Functions way,

let calculateTotal = total => total * 1.1;
console.log(calculateTotal(10)) // 11

See, only the one line of code, and you get the result. No more write ‘function’ and put {} every time you declare function.

You can also do like this way,

let calculateTotal = (total) => {
return total * 1.1;
console.log(calculateTotal(10)) // 11

Now suppose, you don’t have any parameters in your function, then just write this way,

No parameter – ().

One Parameter – (one) or one.

Two Parameters – (one, two).

Let’s see another tiny example with an event.

// Cancel an event

let brickEvent = e => e.preventDefault();
document.querySelector('div').addEventListener('click', brickEvent);

No function or return keywords, sometimes not even needing to add ().

Arrow functions are a great coding shortcut for simple functions.

Leave a Reply

Your email address will not be published. Required fields are marked *