How AI code goes wrong
Lesson 19 Made-up APIs
invented methods and options, wrong library versions
What you'll learn
- Spot methods and options that sound real but do not exist
- Check an unfamiliar call in ten seconds with a REPL
- Notice calls that run but return something else than assumed
AI assistants write method names that sound right. Some of them have never existed. The code looks perfect and fails the first time it runs.
The idea
An AI predicts the next likely word, so it can invent a method that fits the pattern: flatten, contains, unique, groupBy. Others are real, but under another name, or only in a newer version of the language than yours. And some are real and used wrongly: the call works, and the result is not what the code assumes.
You can check an unfamiliar name in ten seconds. Look for the red underline in your editor, or paste the call into a REPL (node, python) and run it on a tiny value. A one-line test beats the docs from memory. Do this for every method you don't know by heart.
1async function weeklyReport(orders) {2 const paid = orders.filter((o) => o.paid);3 const byCustomer = paid.groupBy((o) => o.customerId);4 const names = paid.map((o) => o.name).unique();5 const sent = await Promise.allSettled(paid.map(sendReceipt));6 const totals = sent.map((r) => r.total);7 return { byCustomer, names, totals };8}
- Line 3 Looks reasonable, but arrays have no
groupBymethod. The real one isObject.groupBy(paid, fn). This line throws a TypeError. - Line 4
unique()doesn't exist in JavaScript either. The usual spelling is[...new Set(list)]. - Line 5 Real, but check what it gives back: not your values, but objects like
{ status, value }. - Line 6
r.totalis alwaysundefined. The data is inr.value. No error, just wrong output: worse than a crash.
Take away
- A method that sounds right is not proof it exists. Check it in a REPL.
- Some calls exist under another name or in a newer version than yours.
- A call that runs can still return something else than the code assumes.
Quiz: test yourself
7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.