Coding · Writing code
The Best Prompt for Writing JavaScript or TypeScript
The best prompt for JavaScript settles the things the language leaves open: which runtime, which module system, whether the function is async, and whether it throws or returns on failure. This prompt has the model write the contract first (signature, types and three or four example calls) and then an implementation that honors it without mutating inputs or reaching for APIs your runtime lacks. The reply is a typed function or module, usage examples, and notes on anything that needs checking.
JavaScript and TypeScript Function Prompt
A contract-first prompt: the model fixes the signature, types and error behavior of a function or module before it writes the implementation.
- Works with
- ChatGPT, Claude, Gemini, Cursor
- Difficulty
- Intermediate
- Complexity
- Multi-part reply
- Variables
- 6
- Version
- 1.0
Customize this prompt
Fill in what you know. Anything left blank stays as a [bracketed placeholder]. Nothing you type leaves your browser.
6 variables · fields marked * matter most
You are a senior JavaScript and TypeScript engineer. Write a function or small module to the spec below. ## What I need [What the code should do] ## Environment - Language and module system: [Language and module system] - Runtime: [Runtime] - Signature or example calls I expect: [Expected signature or example calls] - Constraints (dependencies, target version, size, performance): [Constraints] - Existing types or code this must fit with: [Existing types or related code] ## Step 1 - Contract Write this before any implementation: - The exported signature with full types. In plain JavaScript, use JSDoc types. - Three or four example calls with their results, including one failure. - The error contract: for each failure, whether the function throws (and what), rejects, or returns a value that signals failure. Choose one style and keep to it. - Whether it is synchronous or asynchronous, and why. If my expected signature conflicts with the task, say so and propose a correction instead of working around it silently. ## Step 2 - Implementation Write code that satisfies the contract. - Treat arguments as read-only: no mutation of input objects or arrays unless the spec asks for it. - Use only APIs available in the stated runtime. No Node built-ins in browser code, no DOM or window in server code. If an API is recent or not available everywhere, name it and give the minimum version you believe it needs, marked as "check". - No dependencies beyond those the constraints allow. Prefer the platform over a package for anything a few lines can do. - Use const by default, strict equality, and explicit handling of null and undefined at the boundary. - TypeScript: no any, no non-null assertions and no type casts to silence errors. Narrow with checks instead. - Async code: await or return every promise, and do not leave rejections unhandled. - Complete code only. No elided sections, no placeholder comments. ## Step 3 - Review your own work Check each example call from Step 1 against the implementation and correct any mismatch before answering. Then list inputs that could still surprise a caller. ## Reply format 1. Contract 2. Code, in one fenced block per file with the filename above it 3. Usage: a short snippet showing a call and how a failure is handled 4. Notes: assumptions, items marked "check", and anything you would want tested first
Use it when you are
- Writing a utility such as a debounce, a retry wrapper or a date-range helper with a signature you can rely on
- Adding a typed data-transformation function between an API response and your UI state
- Producing a small module that has to run in both Node.js and the browser without bundler surprises
- Replacing a dependency with a few lines of platform code and a clear contract
Why this prompt works
JavaScript has more than one right answer, so the prompt asks which
The same function can be written for a browser or a server, as an ES module or CommonJS, with thrown errors or returned ones. A model given no direction picks whichever is most common in its training data. The Environment block turns each of those forks into an input, so the output matches where the code will actually run.
The contract comes first because it is cheap to review
A signature and four example calls take seconds to read and tell you whether the model understood the job. If the contract is wrong, the implementation would have been wrong too, and you have found out before reading forty lines of code. The examples also give the model something concrete to check its own work against in Step 3.
One error style, chosen out loud
Functions that sometimes throw, sometimes return null and sometimes reject are a common source of bugs in calling code. Making the model pick a single error contract and write it down means callers know what to wrap in try/catch and what to check, and inconsistencies become visible as violations of a stated rule.
Type escape hatches are closed
It is easy to make TypeScript compile by adding any, a cast or a non-null assertion, and generated code often does. Banning them pushes the model toward narrowing with real runtime checks, which is where the actual handling of null, undefined and unexpected shapes ends up being written instead of assumed away.
How to use it
- Describe the behavior in the first field and choose the language and runtime. These two selects prevent most mismatches with your project.
- If you already know how you want to call the function, write that call in the signature field. If not, leave it empty and judge the proposed contract.
- Paste any types the function must accept or return. A real type definition is worth more than a description of one.
- Read the contract section first. Fix the signature or the error behavior there before you spend time on the code.
- Run the example calls from the contract as a quick smoke test, then look up every item marked "check" for your target runtime version.
- Ask for tests as a follow-up, or take the contract to the unit test prompt.
AI model compatibility
| Model | Status | Notes |
|---|---|---|
| ChatGPT | Expected to work | No model-specific adjustment needed. Paste the prompt as written. |
| Claude | Expected to work | If you paste existing types or a neighboring file, put them inside tags such as <existing_code>; Anthropic recommends XML-style tags for keeping reference material apart from instructions. |
| Gemini | Expected to work | Leave the three steps numbered and in order. Google's prompt design guidance favors explicit, sequenced instructions and a defined response format. |
| Cursor | Expected to work | When the function belongs in an existing codebase, point to the file that holds the related types and to your tsconfig or lint rules, so the output follows project settings instead of defaults. |
“Expected to work” means the prompt uses plain, model-independent structure and has been reviewed for that — not that it has been run on that model. A model is marked Tested only when a test record is published below.
Worked example
Scenario: A front-end developer needs a helper that retries a failed network request, to be shared between a web app and a Node.js script.
You are a senior JavaScript and TypeScript engineer. Write a function or small module to the spec below. ## What I need Wrap an async function so it is retried on failure with exponential backoff, up to a maximum number of attempts, and can be cancelled ## Environment - Language and module system: TypeScript (ES modules) - Runtime: Browser and Node.js - Signature or example calls I expect: retry(fn, { attempts: 3, baseDelayMs: 200, signal }) - Constraints (dependencies, target version, size, performance): No dependencies; must not retry if the caller aborts - Existing types or code this must fit with: None - this is a standalone utility ## Step 1 - Contract Write this before any implementation: - The exported signature with full types. In plain JavaScript, use JSDoc types. - Three or four example calls with their results, including one failure. - The error contract: for each failure, whether the function throws (and what), rejects, or returns a value that signals failure. Choose one style and keep to it. - Whether it is synchronous or asynchronous, and why. If my expected signature conflicts with the task, say so and propose a correction instead of working around it silently. ## Step 2 - Implementation Write code that satisfies the contract. - Treat arguments as read-only: no mutation of input objects or arrays unless the spec asks for it. - Use only APIs available in the stated runtime. No Node built-ins in browser code, no DOM or window in server code. If an API is recent or not available everywhere, name it and give the minimum version you believe it needs, marked as "check". - No dependencies beyond those the constraints allow. Prefer the platform over a package for anything a few lines can do. - Use const by default, strict equality, and explicit handling of null and undefined at the boundary. - TypeScript: no any, no non-null assertions and no type casts to silence errors. Narrow with checks instead. - Async code: await or return every promise, and do not leave rejections unhandled. - Complete code only. No elided sections, no placeholder comments. ## Step 3 - Review your own work Check each example call from Step 1 against the implementation and correct any mismatch before answering. Then list inputs that could still surprise a caller. ## Reply format 1. Contract 2. Code, in one fenced block per file with the filename above it 3. Usage: a short snippet showing a call and how a failure is handled 4. Notes: assumptions, items marked "check", and anything you would want tested first
What a good response should contain
- A generic signature that preserves the return type of the wrapped function and types the options object
- Example calls showing success on the first attempt, success after a retry, failure after the final attempt and cancellation
- A stated error contract, for instance that the last error is rethrown and that an abort rejects immediately
- An implementation using only timers and AbortSignal, with a "check" note on the minimum runtime versions for any newer API it relies on
- Notes listing what to test first, such as the delay sequence and behavior when attempts is zero
This is an illustrative scenario showing how to fill in the prompt and what to look for. It is not a recorded model output. Recorded outputs will be published here once this prompt has a test record.
Testing and editorial review
Status: Untested. Reviewed for structure and clarity by the editorial team. No recorded model test yet.
No test record has been published for this prompt yet. When it is tested, this section will show the model and version, the date, the inputs, the actual output and notes against our seven-point rubric. We do not publish numerical scores.
| Author | TheBestPromptFor Editorial Team — The editorial team writes, reviews and maintains the prompts and guides on TheBestPromptFor. Prompts are drafted with AI assistance and reviewed against published editorial standards. |
|---|---|
| Published | November 15, 2026 |
| Last reviewed | November 15, 2026 |
| Last tested | Not yet tested |
| Version history |
|
Limitations and things to check
- The self-review in Step 3 is the model re-reading its own code, not executing it. Run the examples yourself.
- Statements about which runtime version supports an API are recalled from training data and can be out of date. Verify them against current documentation.
- The prompt is sized for a function or a small module. Framework components, build configuration and whole features need a different prompt.
- Code that compiles under your tsconfig may differ from code that compiles under defaults. Strictness settings you do not mention are not taken into account.
Alternative prompts
Coding
Unit Test Writing Prompt
Produces a case inventory first, then readable tests that check behavior at the boundaries, with suspected bugs flagged instead of encoded as passing.
- ChatGPT
- Claude
- Gemini
- Cursor
Coding
Behavior-Preserving Refactoring Prompt
Restructures code in small, named steps while holding its observable behavior fixed, and reports anything it could not prove equivalent.
- ChatGPT
- Claude
- Gemini
- Cursor
Web Development
React Component Prompt
Makes the model plan components, state and effects before coding, then deliver complete files, tests and a list of what it assumed.
- ChatGPT
- Claude
- Gemini
- Cursor
Web Development
Pull Request Code Review Prompt
Reviews a diff the way a careful senior engineer would: intent first, findings ranked by severity, each tied to a line with a suggested fix.
- ChatGPT
- Claude
- Gemini
- Cursor
Related resources
Guide
What Is Prompt Engineering? Core Techniques Explained
What prompt engineering is, the techniques the major model vendors agree on, the working loop behind them, and what prompting cannot fix.
Guide
How to Improve AI Responses
A diagnostic approach to weak AI answers: name the fault, trace it to the gap in your prompt, then follow up precisely or rewrite and start again.
Frequently asked questions
Should I choose TypeScript or JavaScript in the language field?
Choose whatever the file you are adding to uses. If you select plain JavaScript, the prompt still asks for JSDoc types, so editors can check the calls and the contract stays explicit. Mixing a TypeScript answer into a JavaScript codebase usually means stripping types by hand afterwards.
What if I do not know what signature I want?
Leave the field blank. The contract step exists for this case: the model proposes a signature and example calls, and you react to something concrete. It is easier to say "make the options object optional" than to design an interface from nothing.
Does this work for React components or Next.js routes?
It will produce something, but the constraints here are about plain functions and modules. Component state, rendering rules and framework conventions are better handled by the React and Next.js prompts in the web development category.
Sources and references
- JavaScript Guide — MDN Web Docs
- Prompt design strategies — Google AI for Developers
- Prompt engineering overview — Anthropic
Was this prompt useful?
No account needed. Do not include personal information.