Arrow function is a famous ES6 feature.
It is a new syntax for creating functions.
Lets check ES5 & arrow function
ES5 Function declaration:
For ES5 function we no need to assign function to a variable. Without variable we can create simple function ES5
In ES6 arrow function we wont be using function() keyword. It will start with argument followed by '=>' { }
Arrow functions allow us to write shorter function syntax. Which is introduced in ES6.
Before Arrow ES5:
After Arrow ES6:
In ES6 arrow function we must declare with variable as mentioned below.
Arrow function returns the value by default.
Arrow function always anonymous.
Arrow function Expression Syntax:
If the function has only one statement, and the statement
returns a value, you can remove the brackets and the
return
keyword as mentioned below
This works only if the function has only one statement.
Arrow function without parantheses:
It can be written with or without the parentheses with one statement.
const square = x => x*x;
Lets create a regular arrow function and short hand syntax
function name: getFirstName and pass argument on it.
Arrow function using regular function syntax:
Arrow function using short hand syntax:
Let see details of arrow functions
1.Arguments object -> No longer bound with arrow functions.
i.e if you try to access argument it is not going to work.
2.This Keyword -> No longer bound with arrow functions.
const add = function (a,b) {
console.log(arguments);
return a*b;
}
console.log(add(55,1,1001);
This arguments wont be there in ES6 arrow functions.
This argument will show all arguments that we passed in add(55,1,1001) along with it will show value.
This will throw an undefined Error. because arguments no longer bound with ES6 arrow functions.
This Keyword:
lets create a simple user object.
With arrow functions the this
keyword always represents the
object that
defined the arrow function.
Let's see how to loop through array map
map:
map is array method like forEach.
- This useful array method creates a new array with the results of calling a provided function on every element in the calling array.
- It calls a function once for each element in an array.
It
does not execute the function for empty elements.It
does not change the original array.
This function we cant convert arrow function
This is how we need to define ES6 normal function. If we declare arrow function this wont be accessible.
we can use either of below one.
Comments
Post a Comment