Published 8/29/2020 · 2 min read
Tags: javascript
Lambda Expressions vs Anonymous Functions
When learning a functional programming style you will often come across the term Lambda Expressions or Lambda Functions. In simple terms they are just functions that can be used as data and therefore declared as a value. Let’s explore a few examples.
Consider this array of users where each user is stored as an object.
const users = [
{ id: "💻", name: "Gareth", skill: "coder" },
{ id: "🎧", name: "Danny", skill: "DJ" },
{ id: "🕺🏼", name: "Barry", skill: "dancer" },
];
Named Function Declaration
We can use a function declaration to create a named function that can be passed to another function to retrieve some data.
function getUserSkills(user) {
return user.skill;
}
console.log(users.map(getUserSkills));
Anonymous Functions
You will often see and use anonymous functions as callbacks in other functions. Here we are retuning just the user’s skills as a new array of data. These are great for small tasks where you quickly want to grab some data.
console.log(
users.map(function (user) {
return user.skill;
})
);
Lambda Expression
A Lambda expression is an anonymous function assigned to a variable. Here we assign an ES6 anonymous function to the getUserSkills variable. We can then pass the value of getUserSkills to be used as data elsewhere in our application. They become really useful when you want to split out more complex functionality into more readable and reusable functions.
const getUserSkills = (user) => user.skill;
console.log(users.map(getUserSkills));
View on CodePen
Related Articles
- Compressed NFTs: Collections, Verification, and Building a Claim Page
Taking our cNFT minting system to production: creating verified collections, building a web-based claim flow, and preparing for mainnet deployment.
- Building Compressed NFTs on Solana with Generative SVG Art
A practical guide to creating and minting compressed NFTs (cNFTs) on Solana using Metaplex Bubblegum, with animated SVG artwork generated from wallet addresses.
- Learn Svelte & SvelteKit: Course Overview
A complete beginner's guide to Svelte and SvelteKit. From reactivity basics to full-stack applications, learn the framework that compiles away.