Arrow function in Javascript
With ES6 developement the Javascript community came up with the new feature of writing fucntions in Javascript. Arrow functions are the concise alternative to writign functions and solves the problem of this
scope of functions. Since this is a new feature, we will learn how to use the arrow function syntax in diffrent manner to avoid the silly mistakes.
What has changed?
function
keyword has been replaced by =>
but after arguments specifying. That is the basic syntax difference and you can write any ES5 function syntax to arrow function syntax. But that’s not sufficient. The big fat arrow function gives us more flexibility and speedign code writing effieciency.What is that? So.let’s deep dive into that………Quick look over syntax
Syntax based on number of parmeters
x => { … } // omitting parentheses
(x, y) => { … } // more than one parameters
Return statement in arrow function
x => x * x sometimes no need to use block
So for solving all your queries let’s start with a basic function in ES5 and then will write the equivalent ES6 syntax for the same;
When there is no parameters?
You can check that if no parmeters ,then parentheses are required.
var PI_value = function() {
return 3.14;
}
//ES6 syntax
var PI_value = () => {
return 3.14;
}
When single arguments
You can check that with single argument parentheses are not required.
var square = function(a) {
return a * a;
}
//ES6 syntax
var square = (a) => {
return a * a;
}
// more concise way, if we have only one argument, another ES6 syntax
var square = a => {
return a * a;
}
When using multiple arguments
You can check that with single argument parentheses are not required.
var add = function(a, b) {
return a + b;
}
//ES6 syntax
var square = (a, b) => {
return a + b;
}
Return statement and code blocks({})
Having single line return statement we could remove the curly braces and return
statement
var add = function add(a, b) {
return a + b;
};
//ES6 syntax
var add = (a,b) => {return a+b;} //
var add = (a,b) => a+b;// We have omitted curly braces, as well as return keyword
But be cautious, remove both curly braces and return
statement.Removing only curly braces will give an error.
Or, removing only return
keyword keeping the curly brace would not produce the error but no return value.
//ES5 equivalent
var add = function add(a, b) {
a + b;
};
No line break after arrow function arguments
=> {
return a + b;
};
const add = (a, b) => // OK
{
return a + b;
};
const add = (a, b) => { // OK
return a + b;
};
const add = (a, b) => // Ok
a + b;
const add = (a, b) //syntax error
=> a + b;
Use case of arrow function
With array Map functions
return item*item
}
//ES6 arrow syntax
const square = item_array.map( item => item*item )