Functions and each
Make a transformation reusable
A function is a value that accepts arguments and returns a value or raises an error. (x as number) as number => x * 2 defines a function; applying it with (3) after binding it to a name returns 6. as in a signature is a type constraint, not automatic parsing. Optional parameters occur after required ones; if omitted, the argument is null. Choose an explicit default inside the body. each abbreviates a one-parameter function named _. All examples are complete standalone expressions for a blank Power Query query in a disposable Desktop file unless marked otherwise. No account, connector, file or network is required. Expected results are derived, not observed; native M execution and exact Desktop build are NOT RUN.
Select rows with a predicate
let Lines = #table(type table [ID = text, Qty = number], {{"L01", 2}, {"L02", 5}, {"L03", 1}}), Kept = Table.SelectRows(Lines, each [Qty] >= 2), Amounts = Table.AddColumn(Kept, "Amount", each [Qty] * 4, type number)in AmountsExpected:
| ID | Qty | Amount |
|---|---|---|
| L01 | 2 | 8 |
| L02 | 5 | 20 |
The predicate each [Qty] >= 2 means (_) => _[Qty] >= 2. The row is a record. Table.SelectRows retains rows where the condition is true. Table.AddColumn evaluates its generator for each row and produces a new table. The source Lines still has three rows.
Use an optional parameter
let Amount = (qty as number, optional price as nullable number) as number => qty * (if price = null then 4 else price), DefaultPrice = Amount(3), ExplicitPrice = Amount(3, 6), FreeItem = Amount(3, 0)in {DefaultPrice, ExplicitPrice, FreeItem}Expected list: {12, 18, 0}. Both an omitted price and explicit null use the policy default of 4. Zero is a valid supplied price and must not trigger the default. The if ... then ... else expression requires a logical condition; only the selected branch is evaluated. This is a fictional training policy, not a recommendation to impute real missing prices.
Use explicit parameter names for nested expressions
Inside each, [Qty] is shorthand for a field of the current _ argument. A nested each introduces another _, so use named parameters where the intended row might be unclear. Passing Table.SelectRows(Lines, [Qty] >= 2) without a function is not a valid row predicate. When a column can contain null, define an explicit null policy rather than assuming all comparison and logical operators behave like JavaScript.
Practice — Write and test a predicate
Use the same three-row Lines fixture. Write both shorthand and explicit-parameter predicates to keep Qty greater than 2. Add an Amount column using a price of 6. Predict retained IDs and amounts, and check the input row count remains three.
Official reading
functions · conditionals · filter · add · Native execution NOT RUN.