Arrow functions in ECMAScript 6
08 Jul 2016
I think that an arrow functions are one of the best features of ECMAScript 6, excluding class
-es and OOP programming at all.
It has really very helpful and useful syntax for scripting language. So let’s check it out:
Syntax
//Function with no parameters:
() => { statements } ]
//Function with single parameter:
singleParam => { statements }
//Function with one and more parameter:
(param1, param2, …, paramN) => { statements }
//Function with simple return statement:
n => n*2
How did it look in ECMASript 5?
//Function with no parameters:
function() { statements }
//Function with single parameter:
function( singleParam ) { return statements }
//Function with one and more parameter:
function (param1, param2, …, paramN) { return statements }
//Function with simple return statement:
function(n){return n*2}
Use case
I love the syntax of arrow functions in ECMAScript 6! I always asked myself a question why do I need to write word ‘function’ all the time. And now I don’t have to.
Let’s see some examples:
square = n=>n*n;
square(5); //25
This is simple function that returns square of number passed as a parameter. Isn’t it pretty?
In ECMAScript 5 it should be written like this:
function square(n){ return n*n }
But to understand where the new syntax is really helpful, let’s look at injected functions:
//ECMAScript 6:
list.map(item => item*2)
//instead of ECMAScript 5:
list.map(function(item){return item*2})
//ECMAScript 6:
{
list.forEach(n => {
if(n>0){
list2.push(n)
}
})
}
//instead of ECMAScript 5:
(function(){
list.forEach(function(n){
if(n>0){
list2.push(n)
}
})
}()
Don’t you see that ECMAScript 6 is more about program you wrote, not about syntax of it!
* In last example in ECMAScript 6 I used a block-scope, in ECMAScript 5 only function was block scoped. Read more about block-scopes in ECMAScript 6 here: