JavaScript Lambdas
In JavaScript, Lambda is kind of an anonymous function with reduced syntax that looks clutter free.
Syntax
The syntax of a lambda is
(parameters) => returnValue
//or
(parameters) => { returnValue }
This lambda function can be passed as an argument in another function call.
Examples
An example for a lambda function that takes two parameters: a
and b
, and returns a value: a + b
is
(a, b) => a + b
//or
(a, b) => {a + b}
An example for a lambda function that takes no parameters, and returns a value x
is
() => x
An example for a lambda function that takes a single parameter: a
, and returns a value a * a
is
(a) => a * a
//or
a => a * a
In the following example script, we write a lambda function that takes an integer number as argument and returns a boolean value of true if the number is even, or false if the number is odd.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var add = (a, b) => a + b;
var n1 = 4, n2 = 3;
var sum = add(n1, n2);
document.getElementById('output').innerHTML = n1 + ' + ' + n2 + ' = ' + sum;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we have learnt about Lambdas: how to define a lambda function, how to accept parameters and return a value, with examples.