Basic Usage Examples
Learn how to use ExplainThis with these practical examples. Each example demonstrates a common use case and shows how to get explanations using different SDK methods.
Simple Function Explanation
Get an explanation for a basic function
Code to Explain
Source Code
function calculateDiscount(price, percentage) {
const discount = price * (percentage / 100);
return price - discount;
}Using the API
SDK Usage
const response = await fetch('https://api.explainthis.ai/v1/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.explanation);Example Explanation
This function calculates the final price after applying a percentage discount. It takes two parameters: the original price and the discount percentage. First, it calculates the discount amount by multiplying the price by the percentage (converted to decimal). Then, it subtracts the discount from the original price to get the final price.
Array Manipulation
Analyze array filtering and mapping operations
Code to Explain
Source Code
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);Using the API
SDK Usage
import { ExplainThis } from '@explainthis/sdk';
const explainThis = new ExplainThis(process.env.EXPLAINTHIS_API_KEY);
const explanation = await explainThis.explain({
code: code,
mode: 'beginner',
});
console.log(explanation);Example Explanation
This code processes an array of user objects. It first filters the array to include only active users who are 18 or older (adults). Then, it maps the filtered array to extract just the names of these users. The result is an array of names of active adult users.
Async/Await Pattern
Understanding asynchronous code patterns
Code to Explain
Source Code
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;
}
}Using the API
SDK Usage
// Using Python SDK
from explainthis import ExplainThis
client = ExplainThis(api_key='your_api_key')
explanation = client.explain(
code=code,
mode='performance',
language='javascript'
)
print(explanation)Example Explanation
This async function fetches user data from an API. It uses try/catch for error handling and the async/await pattern for cleaner asynchronous code. The function checks if the response is successful (ok), throws an error if not, and parses the JSON response data. Any errors during the process are caught, logged, and re-thrown.
Best Practices
- Always handle API errors appropriately
- Store API keys securely using environment variables
- Consider caching explanations for frequently analyzed code
- Use the appropriate explanation mode for your use case
- Include relevant context when analyzing code snippets