Basic Usage Examples
Learn how to use ExplainThis with these hands-on walkthroughs. Each one shows a common task and how to retrieve explanations through simple HTTP requests.
The examples below cover three scenarios you'll run into regularly: explaining a standalone function, breaking down array transformations, and analyzing asynchronous logic. For every scenario we show the source snippet, the API call that requests an explanation, and the structured response you'll get back. Feel free to copy any of these into your own project as a starting point.
Simple Function Explanation
Get a breakdown for a basic function
Source to Explain
Snippet
function calculateDiscount(price, percentage) {
const discount = price * (percentage / 100);
return price - discount;
}Calling the API
API Walkthrough
const response = await fetch('https://explainthiscode.ai/api/explain', {
method: 'POST',
headers: {
'X-API-Key': process.env.EXPLAINTHIS_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
code: code,
mode: 'standard',
}),
});
const result = await response.json();
console.log(result.summary);Example Explanation
This function figures out the final price after a discount. It takes two inputs: the original price and the discount percent. First, it turns the percent into a decimal and multiplies it by the price. Then it subtracts that amount to get the new price.
Array Manipulation
Analyze array filtering and mapping operations
Source to Explain
Snippet
const users = [
{ name: 'Alice', age: 25, active: true },
{ name: 'Bob', age: 30, active: false },
{ name: 'Charlie', age: 35, active: true },
];
const activeAdults = users
.filter(user => user.active && user.age >= 18)
.map(user => user.name);Calling the API
API Walkthrough
const response = await fetch('https://explainthiscode.ai/api/explain', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.EXPLAINTHIS_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
code,
mode: 'learning',
audience: 'beginner',
language: 'javascript',
}),
});
const explanation = await response.json();
console.log(explanation.sections);Example Explanation
This snippet works with an array of user objects. First, it filters to keep only active users who are 18 or older. Then, it pulls out just the names. The result is an array of names of active adult users.
Async/Await Pattern
Understanding asynchronous program flow
Source to Explain
Snippet
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error('User not found');
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching user:', error);
throw error;
}
}Calling the API
API Walkthrough
const response = await fetch('https://explainthiscode.ai/api/explain', {
method: 'POST',
headers: {
'X-API-Key': process.env.EXPLAINTHIS_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
code,
mode: 'performance',
language: 'javascript',
focus: ['performance'],
}),
});
const explanation = await response.json();
console.log(explanation.metadata);Example Explanation
This async function fetches user data from an API. It uses try/catch for error handling and async/await for cleaner asynchronous logic. The function checks if the response is OK. If not, it throws an error. Otherwise, it reads the JSON data. If anything fails, the error is caught, logged, and re-thrown.
Best Practices
- Always handle API errors properly
- Store your API keys safely using environment variables
- Cache explanations for snippets you analyze often
- Pick the right explanation mode for your goal — Performance mode is especially useful for spotting complexity issues. If you are new to the topic, our post on what Big O notation is is a helpful primer.
- Add useful context when sending source fragments to the API