Lambdas with Arrow Functions in JavaScriptLambdas with Arrow Functions in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Lambda function is a small anonymous function that consist of only one expression and can take one or multiple parameters. They basically allow functions to be passed as parameter to other functions. Since in JavaScript, functions are treated as object so they can be passed and returned from other functions to implement lambda functions.

Following is the code for implementing lambdas with arrow functions in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample,
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
   .sample {
      color: red;
   }
</style>
</head>
<body>
<h1>Lambdas with Arrow Functions in JavaScript</h1>
<div class="sample">[1,2,3,4,5,6,7]</div>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to square the array above</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let sampleEle = document.querySelector(".sample");
   let resEle = document.querySelector(".result");
   let arr = [1, 2, 3, 4, 5, 6, 7];
   let square = (item) => item * item;
   function arraySq(func, arr) {
      let newArr = [];
      arr.forEach((element) => {
         newArr.push(func(element));
      });
      resEle.innerHTML = "The new array = " + newArr;
   }
   BtnEle.addEventListener("click", (event) => {
      arraySq(square, arr);
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −


raja
Published on 18-Jul-2020 11:03:10
Advertisements