In JavaScript, JavaScript Lambda usually refers to an anonymous function. That is a function that is not named and is typically used as a value supplied to another function to pass behavior as a value. Despite the fact that JavaScript was released 20 years ago, it is still the most used language for online development.
JavaScript is used by businesses to generate dynamic and interactive web pages that work across several browsers. JavaScript, with its expanding demand and a plethora of new emerging frameworks, aids programmers in the development of large-scale web applications. In this blog, we’ll bring you more insights on JavaScript Lambda Function.
JavaScript Lambda Function Examples
A JavaScript Lambda Function is a short anonymous function that takes one or more parameters and has only one expression. They essentially permit functions to be provided as parameters to other functions. Because functions are viewed as objects in JavaScript, they can be passed and returned from other functions to create lambda functions.
The Code for Implementing Lambdas using Arrow Functions in JavaScript is shown below:
<!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>
- HTML Structure:
- Displays an array and a button.
.sample
div shows the original array; .result
div is for the output.
- CSS Styling:
- Sets font and color styles.
.sample
text is red, .result
text is blueviolet.
- JavaScript Logic:
- Variables:
BtnEle
targets the button.
sampleEle
and resEle
target the .sample
and .result
divs.
- Array & Function:
arr
holds [1,2,3,4,5,6,7]
.
square
is an arrow function that squares a number.
- Array Processing Function:
arraySq
squares each element using square
, updating newArr
.
- Result displays in
.result
div.
- Button Action:
- On click,
arraySq
is called, updating the .result
div with squared values.
Output
When you click the ‘CLICK HERE‘ button, you will be sent to a new page.
Given below are more examples of using standard JavaScript library routines with Lambda functions for carrying out common operations on arrays and other data structures.
1) Map
This function enables you to transform elements in an array and return a new array with the elements that are transformed. The following example shows doubling the value of each element in an array:
const numbers = [ 3, 4, 5, 6];
const doubled = numbers.map((x) => x * 2);
// doubled is now [6, 8, 10, 12]
- Array Declaration:
numbers
is an array [3, 4, 5, 6]
.
- Mapping Function:
.map()
iterates over each element in numbers
.
- For each
x
, it returns x * 2
.
- Result:
doubled
holds the new array [6, 8, 10, 12]
.
2) Filter
You can use this to choose elements from an array based on criteria and return a new array with those elements. The example below shows choosing all even numbers from an array:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = numbers.filter((x) => x % 2 === 0);
// evens is now [2, 4, 6, 8, 10]
- Array Declaration:
numbers
is an array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.
- Filtering Function:
.filter()
iterates through numbers
, selecting elements where x % 2 === 0
(even numbers).
- Result:
evens
contains [2, 4, 6, 8, 10]
3) Reduce
This function helps you to minimize an array to a single value by applying a function to a single element in the array. The example below shows using the function to calculate the sum of an array of numbers.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, x) => acc + x, 0);
// sum is now 15
4) Sort
This function helps you to arrange the elements of an array in ascending or descending order. This function can be the comparator to specify the sort order. The example below uses a lambda function to sort an array of strings in alphabetical order:
const words = ['apple', 'banana', 'cherry', 'date'];
const sorted = words.sort((a, b) => a.localeCompare(b));
// sorted is now ['apple', 'banana', 'cherry', 'date']
5) Find
You can use this function to find the first element in an array based on conditions. Take a look at the example below in which a lambda function is used to find the first even number in an array:
const numbers = [1, 3, 5, 2, 4, 6];
const firstEven = numbers.find((x) => x % 2 === 0);
// firstEven is now 2
6) Every
Using this function, you can check if every element in an array meets a particular condition. In the example below, you can see that lambda function is used to validate if every element in an array is a string:
const data = ['apple', 'banana', 'cherry', 'date'];
const allStrings = data.every((x) => typeof x === 'string');
// allStrings is now true
7) Some
This function helps you to verify if at least one element in an array meets a certain condition. The example below shows how the lambda function helps to check if there are any odd numbers in an array:
const numbers = [1, 2, 3, 4, 5];
const hasOdds = numbers.some((x) => x % 2 !== 0);
// hasOdds is now true
JavaScript Lambda Function Standard Library Routines
In Javascript, lambda functions are widely utilized in two ways:
- The call to the lambda L is synchronous when a lambda expression (let’s call it L) is supplied as an argument to a function (let’s call it F), and the lambda L is run by function F instantly before the function F returns. So far, the Javascript lambda example in this guide have all been synchronous.
- The call to the lambda L is asynchronous when the function F stores it to be called later so that F can return before L is executed. It frequently occurs after other stored lambda functions have been executed, resulting in a sort of concurrent execution of many jobs. A lambda expression that is run asynchronously is commonly referred to as a “callback.”
Asynchronous callbacks are so common in Javascript that I can’t even begin to list any examples. The async package and the promising design idea are the next areas to investigate.
Benefits of JavaScript Lambda Functions
There are numerous advantages to functional programming. This is why it is being used in computer languages such as JavaScript.
1) JavaScript Lambda Functions Are Pure
One advantage of functional programming is that it allows us to define pure functions in our code.
If we send the same input to a pure function, it always returns the same result.
For example, we could write:
const square = (value) => value ** 2;
We get the value and return its square. This remains constant regardless of what happens outside.
2) JavaScript Lambda Function Code Is Reasonable
The code for the function is completely contained within the function, it is simple to read.
As an example, suppose we have:
const square = (value) => value ** 2;
All we did was square the number passed in. Because there is nothing outside, we can easily inspect it.
3) JavaScript Lambda Function Can Duplicate Code
We don’t have to worry about synchronizing our function’s value with anything outside the function because pure functions don’t rely on any values outside the function.
If we have global values, we may have to do the following:
let global = "something"
let foo = (input) => {
global = "somethingElse"
}
let bar = () => {
if (global === "something") {
//...
}
}
Before we do anything, we must first check the value of the global variable.
We don’t have to do that with pure function because there are no external dependencies.
4) JavaScript Lambda Function Is Cachable
Pure functions always provide the same result when given the same input.
As a result, we can easily cache the function outputs.
const cache = {
1: 2,
3: 4,
//...
}
We just utilize the key as the input and the value as the output. We may simply look up the value in the cache.
5) JavaScript Lambda Function Are Composables
We can easily compose pure functions. We just transmit the result of one pure function to another pure function.
For instance, we could write:
const foo = (a) => {
return a * 2;
}
const bar = (b) => {
return b * 3;
}
We can put the functions together by writing:
foo(bar(100));
It has the appearance of a mathematical function, and it is a mathematical function.
Learn More About:
Conclusion
JavaScript offers a wide range of uses for creating a rich server interface that is simple, popular, and fast. Because there is global support for the developer community, several large corporations, such as Google, established the Angular framework, and Facebook created the React.js framework to consume REST APIs.
When it comes to programming, I’m a big fan of Lord of the Rings especially the “Ring of Power: one language to rule them all.” True, each programming language has advantages and cons, and Javascript began as a quick solution for browser interactivity. You need to make the data analysis-ready before analyzing. Data centralization is the best way for that. Here is where Hevo can help you.
Hevo is the only real-time ELT No-code Data Pipeline platform that cost-effectively automates data pipelines that are flexible to your needs. With integration with 150+ Data Sources, the platform also helps you to transform & enrich your data, & make it analysis-ready.
Visit our Website to Explore Hevo
Want to take Hevo for a spin? Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand. You can also have a look at our unbeatable pricing that will help you choose the right plan for your business needs!
Share your learning experience of JavaScript Lambda Functions in the comment section below!
References
- https://www.boltic.io/blog/lambda-function-javascript
Frequently Asked Questions
1. What does the => mean in JavaScript?
The =>
symbol in JavaScript is used to define arrow functions. Arrow functions provide a concise syntax for writing functions and have some key differences compared to traditional function expressions.
2. Why does JavaScript use so many lambda functions?
JavaScript uses many arrow functions because they simplify code, handle this binding better, and fit well with functional programming styles.
3. Why use the lambda function?
Lambda (arrow) functions are used for conciseness, lexical this binding, and aligning with functional programming practices.
Davor DSouza is a data analyst with a passion for using data to solve real-world problems. His experience with data integration and infrastructure, combined with his Master's in Machine Learning, equips him to bridge the gap between theory and practical application. He enjoys diving deep into data and emerging with clear and actionable insights.