Lambda

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Arrow Functions

JS · Functions
syntax
const fn = (params) => expression;
const fn = (params) => { ... };
example
const double = n => n * 2;
console.log(double(7)); // 14

const greet = (name, greeting = "Hello") => `${greeting}, ${name}!`;
console.log(greet("Ava")); // "Hello, Ava!"

// Return an object literal (wrap in parentheses)
const makeUser = (name, id) => ({ name, id });
console.log(makeUser("Bo", 1));

Note Arrow functions have no own this, arguments, or super. They inherit this from the surrounding scope, making them unsuitable as object methods or constructors.

PYPython

Lambda (Anonymous Functions)

PY · Functions
syntax
lambda params: expression
example
square = lambda n: n ** 2
print(square(5))

users = [{"name": "Carol", "age": 28}, {"name": "Alice", "age": 35}]
users.sort(key=lambda u: u["age"])
print([u["name"] for u in users])
output
25
['Carol', 'Alice']

Note Lambdas are limited to a single expression. For anything with statements or multiple lines, use a regular def. Assigning a lambda to a variable is less readable than def.