Sub topic 3
Passing parameters and returning data
This chapter assumes you can write basic Apex (classes, SOQL, DML) and a Lightning web component class with decorators. It also assumes you know how @AuraEnabled marks a method as callable and what the static, public or global rules mean. Here you will learn how values cross the boundary between JavaScript and Apex, which types work, and which mistakes cause silent null values or missing fields.
How data crosses the boundary
A call from a component to Apex is a network request. The platform serializes the parameters you pass in JavaScript to JSON. It then deserializes them into Apex types, runs your method, serializes the return value to JSON, and hands it back to JavaScript as an object.
Because the data passes through JSON, anything JSON cannot represent either gets converted or is not supported. Two consequences follow:
- Apex types and JavaScript types do not map one to one.
- Only the data travels. Methods, private members, and object identity do not.
Matching parameters by name
The component passes one object whose property names must match the Apex parameter names exactly. Matching is by name, not by position.
// Apex signature: findOpportunities(SearchFilter filter, Integer maxRows)
findOpportunities({ filter: myFilter, maxRows: 25 });Three behaviors cause most parameter bugs:
- A misspelled or wrongly cased property is ignored. If you pass
maxrowsinstead ofmaxRows, the call still succeeds, and Apex receivesnullformaxRows. Treatnullas a normal input in every method. - A property set to
undefinedis dropped. Apex seesnull. - Extra properties are ignored. Apex does not warn you about them.
Apex parameter names are not checked at compile time against your JavaScript. A rename in Apex breaks the component only at run time.
Supported parameter types
| Apex parameter type | What JavaScript passes | Notes |
|---|---|---|
| `String`, `Boolean` | string, boolean | Direct match. |
| `Integer`, `Decimal`, `Double` | number | Send a number, not a numeric string. |
| `Long` | number | JavaScript numbers lose precision above 2^53, so avoid very large values. |
| `Id` | string | An invalid Id string causes an error before your method runs. |
| `Date` | string such as `'2026-12-31'` | ISO 8601 format. |
| `Datetime` | ISO 8601 string | Include the time zone, for example `'2026-12-31T09:30:00.000Z'`. |
| `List<T>` | array | Elements must convert to `T`. |
| `Map<String, T>` | object | Keys must be strings. |
| `SObject` or a specific sObject type | object with field names as properties | Field names use API names. |
| Apex class with `@AuraEnabled` members | object with matching properties | Members without `@AuraEnabled` are not populated. |
Some types do not work as parameters or return values. Blob is the common one. If you need to move binary data, use a base64 String.
Passing structured input with a class
When a method needs several related values, a small input class is easier to maintain than a long parameter list. Adding a field later does not change the method signature. The class below holds the search criteria for the example in this chapter.
public with sharing class OpportunitySearchController {
public class SearchFilter {
@AuraEnabled public String stageName;
@AuraEnabled public Decimal minAmount;
@AuraEnabled public Date closeBefore;
}
@AuraEnabled(cacheable=true)
public static List<Opportunity> findOpportunities(SearchFilter filter, Integer maxRows) {
if (filter == null || String.isBlank(filter.stageName) || filter.closeBefore == null) {
throw new AuraHandledException('A stage and a close date are required.');
}
String stage = filter.stageName;
Date lastDate = filter.closeBefore;
Decimal minimum = filter.minAmount == null ? 0 : filter.minAmount;
Integer rowLimit = (maxRows == null || maxRows < 1 || maxRows > 200) ? 50 : maxRows;
return [
SELECT Id, Name, StageName, Amount, CloseDate, Account.Name
FROM Opportunity
WHERE StageName = :stage
AND CloseDate <= :lastDate
AND Amount >= :minimum
WITH USER_MODE
ORDER BY CloseDate
LIMIT :rowLimit
];
}
}The method validates its inputs first. Never assume the client sent sensible values. A user can call the method with any parameters through browser tools, so the Apex side is the only place where validation is reliable. The method also clamps maxRows to a range so a client cannot request an unbounded query.
The component calls it imperatively and converts a form value into the expected shapes:
import { LightningElement } from 'lwc';
import findOpportunities from '@salesforce/apex/OpportunitySearchController.findOpportunities';
export default class OpportunitySearch extends LightningElement {
opportunities = [];
error;
async handleSearch() {
const filter = {
stageName: 'Prospecting',
minAmount: 10000,
closeBefore: '2026-12-31'
};
try {
this.opportunities = await findOpportunities({ filter, maxRows: 25 });
this.error = undefined;
} catch (e) {
this.error = e.body ? e.body.message : e.message;
this.opportunities = [];
}
}
}What comes back
Apex serializes the return value and the component receives the result as a JavaScript value.
| Apex return type | JavaScript receives |
|---|---|
| `String`, `Boolean`, `Integer`, `Decimal` | string, boolean, number |
| `Id` | string |
| `Date`, `Datetime` | string (ISO 8601) |
| `SObject` | object with the queried fields |
| `List<T>` | array |
| `Map<String, T>` | object |
| Apex class | object with the `@AuraEnabled` members |
| `void` | `undefined` (non-cacheable methods only) |
A method marked cacheable=true must return a value. void is allowed only for methods that are not cacheable.
sObjects contain only the fields you queried
The returned record has only the fields in your SELECT list, plus Id. In the example, opp.Amount works, but a field you did not select is undefined in JavaScript. Apex itself throws an SObjectException if you read an unqueried field on the server.
Parent fields arrive as nested objects. The Account.Name selected above is read as opp.Account.Name. If an opportunity has no account, opp.Account is undefined, so guard the access. In a template, use opp.Account.Name with care, or read it in JavaScript with optional chaining: opp.Account?.Name.
Child records selected in a subquery arrive as an array under the relationship name. The subquery (SELECT Id FROM Contacts) becomes account.Contacts. When an account has no contacts, the property is missing, so account.Contacts is undefined, not an empty array.
Maps and aggregate results
A Map<String, T> becomes a plain JavaScript object, which suits count-by-category data. The example below returns the number of opportunities per stage. It converts the AggregateResult rows to a map on the server, so the client does not need to know about that Apex type.
public with sharing class OpportunitySummaryController {
@AuraEnabled(cacheable=true)
public static Map<String, Integer> countByStage(Id accountId) {
Map<String, Integer> counts = new Map<String, Integer>();
for (AggregateResult row : [
SELECT StageName stage, COUNT(Id) total
FROM Opportunity
WHERE AccountId = :accountId
WITH USER_MODE
GROUP BY StageName
]) {
counts.put((String) row.get('stage'), (Integer) row.get('total'));
}
return counts;
}
}In JavaScript the result is { Prospecting: 3, Closed Won: 1 }. Use Object.entries(result) to turn it into an array you can iterate in a template. Templates cannot loop over plain objects.
Wrapper classes
When the result does not match a single sObject, return an Apex class. Its members are included only if marked @AuraEnabled. The next chapter covers wrapper classes in detail.
Read-only results and mutation
Data delivered through @wire is frozen. Assigning to a property of a wired record, or sorting a wired array in place, throws an error in strict mode. Copy before changing it:
const sorted = [...this.wiredOpportunities.data].sort(
(a, b) => (b.Amount ?? 0) - (a.Amount ?? 0)
);For a nested record, copy each level you change, for example { ...opp, Name: 'New name' }. Results from imperative calls are ordinary objects and can be changed, but copying is still safer when the same data feeds several parts of the component.
Reactive parameters with @wire
With @wire, a parameter value that starts with $ is read from a component property, and the wire reruns when that property changes. Two rules matter:
- If a reactive property is
undefined, the wire does not call Apex at all. This is useful becauserecordIdis not yet set when the component first loads. If you passnull, Apex is called and receivesnull. - The wire reruns when the property is reassigned to a new value. Mutating an object in place does not trigger it. When a reactive parameter is an object, assign a new object:
this.filter = { ...this.filter, stageName: 'Qualification' };.
Common mistakes
- Wrong parameter name. Apex gets
null, and the failure appears later as a null pointer exception or an empty result. - Passing a non-ISO date string.
'12/31/2026'fails conversion. Format dates in JavaScript asYYYY-MM-DD. - Reading unqueried fields. The value is
undefinedon the client. - Returning a class without
@AuraEnabledmembers. The component receives an empty object. - Returning too much. Every returned row and field is serialized and sent to the browser. Select only the fields the component uses, and limit the rows.
- Trusting parameters. A client-supplied
Idor filter value should be validated, and the query should run with the user's permissions.
Exercise
A component calls getContacts({ accountID: this.recordId }), but the Apex method is declared as getContacts(Id accountId). The call succeeds and returns an empty list. What is the cause, and how do you fix it?
Show answer
The JavaScript property accountID does not match the Apex parameter name accountId, so the platform ignores it and passes null to the method. The SOQL filter AccountId = null matches no contacts, which gives an empty list instead of an error. Rename the property to accountId so the names match exactly, including case. You can also add a null check in Apex that throws an AuraHandledException, so a mismatch fails loudly.
Exercise
A wired method returns a list of opportunities. A developer calls this.wiredOpportunities.data.sort(...) and gets an error. Why, and what should they do instead?
Show answer
Data delivered by @wire is read-only, and sort changes the array in place. Copy the array first and sort the copy, for example [...this.wiredOpportunities.data].sort(...).