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.

Frequently asked questions

How does JavaScript handle lambda?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Arrow Functions" snippet in JavaScript uses `const fn = (params) => expression;`.
Which code does the JavaScript example use?
The "Arrow Functions" snippet uses `const fn = (params) => expression;`, from the Functions section of the JavaScript cheat sheet.
Which stacks cover "lambda" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Arrow Functions": Arrow functions have no own this, arguments, or super. They inherit this from the surrounding scope, making them unsuitable as object methods or constructors.