[Solved] Give examples of Arrow (Lambda) Functions in JavaScript

  

5
Topic starter

Can you please give an example or examples of Arrow (Lambda) Functions in JS. I know that JavaScript functions can be written in short form using "=>" (arrow). This is the short syntax for anonymous functions.

4 Answers
6

Here is my example:

this is JS function:

let f = function (a, b) {
    return a + b;
};
 
console.log(f(5, 6));

and this is the same function but with arrow (lambda):

let q = (a, b)=>a + b;
console.log(q(5, 6));

Another 3 examples:

//example with array and forEach:
[10, 20, 23, 432, 343, "text"].forEach(x=>console.log(x));
 
//example with .filter:
console.log([10, 20, 30].filter(a=>a > 15));
 
//example with .map:
console.log([10, 20, 30].map(a=>a * 2));
Hope you get it

Hope you get it

3
let sum = (a, b)=> a + b;
console.log(sum(5, 16));
3

Mine:

let increment = function (x) {
    return x + 1;
};
 
console.log(increment(6));

The same as the above - but with lambda (shortens the code):

let incrementTwo = x => ++x;
console.log(incrementTwo(6));
2

Here is an example from my WordPress project of the ES6 arrow function syntax (you do not need to name it - it can be anonymous):

setTimeout(() => this.searchField.focus(), 301);
Share: