What is the Arrow Function in JavaScript? | Salesforce Developer Guide
Arrow function is the way to write a function in a shorter manner/syntax. It is simple and easy to use and understand. Here are some examples and comparisons:
Normal Function:
function abc() { return “I am inside a normal function”; }
Arrow function:
- 1st way (with return):
abc = () = > { return “I am inside a normal function”; }
- 2nd way (without return):
abc = () = > “I am inside a normal function”;
Arrow function with parameters:
Single parameters:
abc=data=> { return data+10; }
OR
abc=(data)=> { return data+10; } console.log(abc(5)); // calling statement
We can use small brackets around parameters or not in single parameter but in case of multiple parameters you have to use () small brackets parameters.
Don't forget to check out: Javascript for Lightning Web Component | Salesforce Lightning
Multi parameters:
abc = (data1, data2) => { return data1+data2+10; } console.log(abc(4,5)); // calling statement
In the case of arrays:
arr = [1,2,3,4]; let newarr = arr.map((item)=>item*2) // without return console.log(newarr);
OR
let newarr = arr.map((item)=> { return item*2; }) // with return
Benefits of Arrow Function:
- Arrow syntax automatically binds this to the surrounding code’s context.
- Easy to write and understand.
Problem Solved by Arrow function:
There is a problem with the normal function if we define a variable and a function in the same scope then the function can access that variable but inside that function, if we define another function then it shows undefined.
Example:
let obj ={ name: “sample”, getname:function() { console.log(this.name); function fullname(){ console.log(this.name); console.log (“my full name is ”+this.name+” surname.”); } fullname() //calling inner function } } obj.getname(); //calling outer function
Check out another amazing blog by Pranjal: Aura Vs LWC: Why You Should Learn LWC? | Salesforce Lightning Tutorial
Output:
sample
undefined
my full name is undefined surname.
To solve this problem, we use the arrow function instead of the normal function.
If I convert the inner function into an arrow function then it remembers the value of the name inside the inner function.
Example:
let obj = { name: “sample”, getname:function() { console.log(this.name); const fullname=()=> { console.log(this.name); console.log (“my full name is ”+this.name+” surname.”); } fullname() //calling inner function } } obj.getname(); //calling outer function
Responses