Consider the below given function:
const myFunc = function() {
const myVar = "returnValue";
return myVar;
}
Instead of the above syntax we can use ES6 syntax as:const myFunc = () => {
const myVar = "returnValue";
return myVar;
}
The arrow function syntax allows us to completely omit the return statement:const myFunc = () => "value"
We can use arrow functions to write concise and small functions very clearly in LWC.Higher Order Functions
By definition Higher Order functions are functions that accepts and/or returns another function.
1. Map Function
The map() method creates a new array with the results of calling a function for every array element.
The syntax for the method is:
array.map(function(currentValue, index, arr), thisValue)
- currentValue (required): The value of the current element
- index (optional): The array index of the current element
- arr (optional): The array object the current element belongs to
- thisValue (optional): Value to use as this when executing callback.
import { LightningElement, track } from 'lwc';
export default class App extends LightningElement {
connectedCallback(){
let a = [1,2,3,4];
a.map(this.findSquare);
}
findSquare(item){
console.log(item*item);// 1,4,9,16
}
}
We can shorten the above code further by using the arrow functions that we just learnt!import { LightningElement, track } from 'lwc';
export default class App extends LightningElement {
connectedCallback(){
let a = [1,2,3,4];
a.map(item => console.log(item*item));// 1,4,9,16
}
}
2. Filter functionThe filter() method creates a new array with all elements that pass the test implemented by the provided function.
The syntax for this method is:
array.filter(function(currentValue, index, arr), thisValue)
The arguments are similar to map function.
import { LightningElement, track } from 'lwc';
export default class App extends LightningElement {
connectedCallback(){
let arrayNumber = [2,5,67, 8, 90];
const evenArray = arrayNumber.filter(item => item%2 === 0);
console.log(evenArray); // 2,8,90
}
}
3. Reduce functionThe reduce() method reduces the array to a single value.
The reduce() method executes a provided function for each value of the array (from left-to-right).
The syntax for this function is:
array.reduce(function(total, currentValue, currentIndex, arr),initialValue)
- total (required): The initialValue, or the previously returned value of the function
- currentValue (required) : The value of the current element
- currentIndex (optional) : The array index of the current element
- arr (optional) : The array object the current element belongs to
- initialValue (optional) : A value to be passed to the function as the initial value
import { LightningElement, track } from 'lwc';
export default class App extends LightningElement {
connectedCallback(){
let arr = [1, 2, 3, 4];
let total = arr.reduce( (sum, current) => sum += current ) ;
console.log(total); // 10
}
}
The code examples can be found here.
0 comments:
Post a Comment