Writing Functions with AI Help
AI assistants can produce solid function drafts quickly when you give them clear input, output, and constraint specifications.
Writing functions with an AI assistant is one of the most practical uses in a developer's day-to-day work. The key is treating the output as a draft that needs review, not finished code.
Writing a useful function prompt
Specify the language and version if it matters. State what the function takes as input and what it returns. List the edge cases to handle. Name any libraries to use or avoid. If the function must follow a specific interface or naming convention, state that too.
Vague: "Write a function to format a date." Clear: "Write a JavaScript function that takes a Date object and returns a string formatted as YYYY-MM-DD. Handle null input by returning an empty string."
The clearer version produces a more useful, predictable result with far less back-and-forth.
Reading AI-generated functions before using them
Read through the logic once before running it. Check: does it handle the edge cases you care about? Does it make assumptions about the input that are not always true? Does it use patterns or APIs that fit your codebase?
If you do not understand part of the function, ask the assistant to explain it. Do not ship code you cannot explain.
A concrete example
A developer needs a function that takes an array of numbers and returns the median. They ask: "Write a JavaScript function that takes an array of numbers and returns the median. Handle empty arrays by returning null. No external libraries." The result is a function that sorts the array and returns the middle element, with a check for empty input.
code: | function median(nums) { if (!nums || nums.length === 0) return null; const sorted = [...nums].sort((a, b) => a - b); const mid = Math.floor(sorted.length / 2); return sorted.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; } console.log(median([3, 1, 4, 1, 5])); console.log(median([1, 2, 3, 4])); console.log(median([])); codeOutput: "3\n2.5\nnull" canRun: true
Try it
Pick a small utility function your current project needs. Write a prompt with the language, input type, output type, and at least two edge cases to handle. Review the output before running it.
Quick check
What is the most important thing to specify when asking AI for a function?
Quick check
After getting an AI-generated function, what should you check first?

