settingsAccountsettings
Menusettings

Q: Give examples of Arrow (Lambda) Functions in JavaScript

+5 votes
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.
asked in JavaScript category by user matthew44

3 Answers

+4 votes

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

answered by user ak47seo
+2 votes
let sum = (a, b)=> a + b;
console.log(sum(5, 16));

 

answered by user hues
+1 vote

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));
answered by user samfred5830
...