The best JavaScript prompts say where the code runs, paste the real code and ask for an answer you can check, like a rewrite plus a list of behavior changes. Below are 12 JavaScript prompts for ChatGPT, Claude, Claude Code and Codex covering modern syntax, async code, cancellation, race conditions, the DOM, memory leaks, ES modules and tooling.
For general jobs such as explaining code, debugging a stack trace and writing a regex, see the coding prompts. For large cleanups, the refactoring prompts go deeper. The prompts here are specific to JavaScript.
How to use these prompts
Copy a prompt, replace each blank in double braces, or keep the default after the colon. {{runtime:modern browsers}} means modern browsers unless you change it.
Three habits make the answers better:
- Say where it runs. Browser targets or a Node.js version decide which built-ins are safe. MDN shows a Baseline badge on most feature pages; Array.prototype.toSorted(), for example, is listed as widely available since July 2023.
- Paste the real code and output. Console errors, network timings and heap snapshot summaries are better than descriptions.
- Ask for behavior changes. JavaScript has many quiet differences, such as
sort()comparing elements as strings by default. A list of what could behave differently is the fastest review.
In an agent, name the files and let it run the tests itself.
How do you modernize JavaScript with AI?
1. Modernize old JavaScript
For code from before ES2015 habits faded. The list of behavior changes is the part to review.
Modernize this JavaScript for {{runtime:modern browsers}}:
- var to const or let
- callbacks and .then chains to async/await
- prototype assignments to classes
- string concatenation to template literals
- manual loops to array methods where it reads better
Do not change behavior. After the code, list every place where the new
version could behave differently (scoping, this binding, hoisting, error
handling), even if it is unlikely.
{{code}}
2. Explain surprising behavior
For the "why does this print that" moments: this, closures, hoisting and type coercion.
This JavaScript does something I didn't expect.
Code:
{{code}}
Expected: {{expected}}
Actual: {{actual}}
Explain step by step what the engine does, naming the rule involved (for
example coercion, closure capture, hoisting or this binding). Then show the
fixed code and one sentence I can remember to avoid this next time.
3. Replace a library with built-ins
For dropping a dependency you use for two functions. Checking browser support keeps it from breaking older targets.
I use {{library:lodash}} only for these functions: {{functions}}.
Rewrite each call using built-in JavaScript for {{runtime:modern browsers}}.
For each built-in you use, say whether it is Baseline widely available on
MDN. Where the built-in behaves differently from the library (deep vs
shallow copy, handling of null or undefined), point it out and show a test
case.
{{code}}
How do you write async JavaScript that doesn't break?
4. Run tasks in parallel with a limit
For loops that await one request at a time, or fire hundreds at once. The Promise.allSettled() page explains when to prefer it over Promise.all().
This code processes {{count:500}} items with an await inside a loop, so it
runs one at a time. Rewrite it to run at most {{limit:5}} at once without
adding a dependency.
Decide between Promise.all and Promise.allSettled for this case and say
why. Failed items should {{on_failure:be collected and reported at the end}}.
Keep results in the same order as the input.
{{code}}
5. Add cancellation and timeouts to fetch
For requests that hang or keep running after the user leaves. AbortController lets you abort fetch requests through its signal.
Add cancellation and timeouts to this fetch code.
- Abort the request after {{timeout_ms:8000}} ms.
- Also abort when {{cancel_event:the user navigates away or starts a new search}}.
- Use AbortController and AbortSignal; no extra libraries.
- Tell apart a timeout, a user cancel and a network error in the error
handling, and don't show an error message for a user cancel.
- Check browser support for each API you use.
{{code}}
6. Fix stale responses in search-as-you-type
A classic race condition: a slow early response overwrites a fast later one.
In this {{framework:vanilla JavaScript}} search box, results sometimes show
an older query than the one typed. Explain the race condition step by step
with a timeline. Then fix it so only the latest request can update the
screen, cancel requests that are no longer needed, and debounce input by
{{debounce_ms:250}} ms. Show how to reproduce the bug with a fake slow
server.
{{code}}
How do you fix browser and DOM problems?
7. Build a small DOM component without a framework
For a widget that doesn't justify a framework. Accessibility requirements go in the prompt or they get skipped.
Build a {{component:dropdown menu}} in plain JavaScript, HTML and CSS.
- Use event delegation, not one listener per item.
- Keyboard support: {{keys:arrow keys, Enter, Escape and Tab}}.
- Correct ARIA roles and states, and visible focus.
- A destroy() method that removes every listener it added.
- No frameworks or dependencies.
Explain the accessibility choices in a short list.
8. Find a memory leak in a single-page app
For memory that grows each time a view opens. Common causes are listeners, timers and caches that outlive the view. MDN's memory management guide explains reachability and when WeakMap helps.
Memory in my {{framework:vanilla JavaScript}} app grows by about
{{growth:20 MB}} each time I {{action:open and close the settings panel}}.
Heap snapshot comparison summary:
{{snapshot_summary}}
Code for that view:
{{code}}
List the likely leaks, ranked, with the line of evidence for each: event
listeners, timers, observers, closures, global caches or detached DOM
nodes. For each, show the cleanup code and where to call it.
How do you handle modules and tooling?
9. Convert a CommonJS package to ES modules
For moving require code to import. ES modules run in strict mode automatically, which can surface hidden bugs.
Convert this {{runtime:Node.js 22}} package from CommonJS to ES modules.
Give me:
- The package.json changes
- Each file converted (require to import, module.exports to export)
- Replacements for __dirname, __filename and require.resolve
- How to keep supporting CommonJS consumers, if I need that:
{{dual_package:no}}
- Anything that will behave differently, such as strict mode, top-level
this or JSON imports
{{code_or_file_list}}
10. Add types with JSDoc
For type safety without a TypeScript build step. The TypeScript handbook shows how JSDoc comments plus // @ts-check turn on type errors in plain .js files.
Add JSDoc type annotations to this JavaScript so it passes TypeScript's
checker with // @ts-check at the top of each file.
- Use @typedef for repeated object shapes.
- Type every exported function's parameters and return value.
- No any. If a type is unclear, ask me instead of guessing.
- Do not change runtime code.
List any bugs the types revealed.
{{code}}
11. Shrink a JavaScript bundle
For slow first loads. Paste the bundle analyzer output, not a guess.
My {{bundler:Vite}} production bundle is {{size:900 KB}} gzipped. Target:
{{target:under 250 KB}} for the first page.
Bundle analyzer output:
{{analyzer_output}}
package.json dependencies:
{{dependencies}}
Rank the changes by bytes saved: replacing heavy dependencies, lazy loading
routes with dynamic import(), fixing imports that block tree shaking, and
removing polyfills my targets don't need. Estimate the savings for each.
12. Validate untrusted input
For JSON from an API, form fields or URL parameters. Validation at the edge keeps bad data out of the rest of the code.
Write validation for this input in JavaScript, using
{{library:no library, plain code}}.
Shape I expect:
{{shape}}
Where it comes from: {{source:a public API request body}}
Reject unknown fields, check types, lengths and ranges, and return all
errors at once with the field path for each. Never trust the input for
anything until it passes. Include five test inputs that should fail and
why.
What should you check before you ship the answer?
AI-written JavaScript tends to fail in the same few places, so check them every time:
- Browser support. Look up any built-in you don't recognize on MDN and check its Baseline status against your targets.
- Error paths. Make sure every
awaitsits inside error handling that does something useful, and that rejected promises are never silently dropped. - Cleanup. Every listener, timer and observer the code adds should have a matching removal.
- Tests. Run the existing suite, and ask for a test that fails on the old code and passes on the new.
Turn your favorite one into a skill
When one of these becomes a daily habit, make it a skill so Claude Code or Codex uses it automatically. The modernize and cancellation prompts are good first candidates. Paste one into the free SKILL.md generator and it becomes a valid SKILL.md. For React projects, the React best practices skill covers framework-level patterns. For tests, see the unit test prompts.
To keep prompts like these close, save them in Kipt: your library lives as Markdown in a private GitHub repo you own, {{blanks}} stay fillable, and Cmd+K finds any prompt by name or tag.