top of page
Writer's pictureSaurabh Singh

Arrow function in Lightning Web Component (LWC)

Arrow functions are compact alternatives to regular JavaScript functions. The advantage of arrow functions is that it does not bind its own this.


Let's understand with an example.


this is regular function expressions ->

import { LightningElement, track, api } from 'lwc';
export default class App extends LightningElement {

// Event will be fired on button click
handleClick(event) {
 let myName = new this.Employee('Saurabh'); 
 myName.info();  
}

Employee = function(__name) { 
 this.my_name = __name; 
 this.info = function() { 
         console.log(this.my_name);  // print Employee data
         setTimeout(function() { 
         // here this does not refer to Employee
           console.log(this.my_name); 
          }, 100); 
        } 
    }
}

output


Saurabh undefined


The reason why we get undefined for setTimeout function logs because it has normal function invocation and the this context is set to window object.


we can fix this issue with arrow function invocation. Just change the setTimeout function syntax to following.



setTimeout(() => { 
 // here this=Employee
           console.log(this.my_name); 
          }, 100);  

output


Saurabh

Saurabh


Now let's understand different types of arrow functions.


1. Basic - This type of arrow function don't have any body and just have one statement. Below function is returning sum of two variable.


handleClick(event) {
    console.log(this.sum(2,6));
}

sum = (a, b) => a + b;

*******************
output
8


hello = () => {
  return "Hello World!";
}

Or

hello = () =>"Hello World!";

//Basic function with parameter

hello = (val) =>"Hello "+ val;

2. Advance -


Example 1 - use arrow function to generate map

import { LightningElement, track } from 'lwc';

export default class App extends LightningElement {
States = [
 'Delhi',
 'United Province',
 'Punjab',
 'Jammu and Kashmir'
];

handleClick(event)
{
 let mp = this.States.map(state => state.length);
 console.log('Size of each map Item->');
 for(let i=0; i<mp.length;++i)
    {
        console.log(mp[i]);
    }
 
}
}

output


Size of each map Item->
5
15
6
17

Example 2 - use arrow function to sort.

let numbers = [4,2,6];
numbers.sort((a,b) => b - a);  // this is the compare function in JS
console.log(numbers); // [6,4,2]

numbers.sort((a,b) => b - a) this is to sort in ascending order. for descending order use

numbers.sort((a,b) => a - b);

6,314 views0 comments

Comments


bottom of page