Arrow Functions in ES6

Arrow functions provide a concise way to define a function in JavaScript. Here I am going to create a new function to multiply 2 numbers.

1
2
3
4
function multiply (a, b) {
    return a * b;
}
console.log(multiply(2, 4)); // 8

The same multiplyfunction can be defined using arrow syntax. It is more compact.

1
2
3
var multiply = (a, b) => a * b;
console.log(multiply(2, 4)); // 8

Just compare the two ways. You can relate few things. The arguments are wrapped in parenthesis. The return value is placed after the arrow(=>).

Note:Parenthesis is NOT needed if there is only one argument.

1
2
3
var square = a => a * a;
console.log(square(2)); // 4

Note:If you do not want to pass an argument, just type empty parenthesis.

1
2
3
var humpty = () => 'dumpty';
console.log(humpty()); // 'dumpty'

You may also like...

Leave a Reply

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