Skip to main content
JavaScript Prompts

ChatGPT Prompts for JavaScript Developers

Master modern JS. These prompts help with async patterns, React components, Node.js APIs, and TypeScript migrations.

12 prompts|Updated March 2026

JavaScript powers the web. Whether you're building React apps, Node.js APIs, or vanilla JS interactions, these prompts help you write cleaner, more performant code. Each prompt targets real development challenges — from debugging closure issues to optimizing bundle size.

1

Async/Await Error Handling Pattern

Refactor the following JavaScript code to use a robust async/await error handling pattern.

Current code:
[paste your async code here]

Requirements:
1. Replace raw try/catch blocks with a reusable error handler utility (e.g., a wrapper function that returns [error, data] tuples)
2. Handle specific error types differently (network errors, validation errors, timeout errors)
3. Add retry logic for transient failures with exponential backoff
4. Ensure all errors are logged with enough context to debug in production (function name, input params, timestamp)
5. Preserve the original stack trace — do not swallow errors silently

Provide the refactored code, the utility function, and a brief explanation of why this pattern is more maintainable than nested try/catch blocks.
Specify whether you're working in a browser environment or Node.js, since error types and logging strategies differ significantly.
2

React Custom Hook Builder

Create a custom React hook called use[HookName] that handles the following functionality:

**Purpose:** [describe what the hook does, e.g., "manages paginated API data with infinite scroll"]

**Requirements:**
1. Accept configuration options as a parameter object with sensible defaults
2. Return a clear interface: { data, loading, error, and any action functions }
3. Handle cleanup properly — cancel pending requests on unmount using AbortController
4. Memoize expensive computations and callback references with useMemo and useCallback
5. Include TypeScript-ready JSDoc annotations for all parameters and return values
6. Follow the Rules of Hooks — no conditional hook calls

**Context:**
- React version: [18/19]
- Data fetching: [fetch / axios / SWR / React Query]
- State shape: [describe the data structure]

Provide the complete hook, a usage example in a component, and notes on any edge cases (race conditions, stale closures).
Mention whether you need SSR compatibility — hooks that use window or document need conditional checks in Next.js.
3

Node.js REST API Endpoint

Write a production-ready Node.js REST API endpoint for the following resource.

**Resource:** [e.g., "User profiles" or "Product reviews"]
**Framework:** [Express / Fastify / Hono / vanilla http]
**Database:** [PostgreSQL / MongoDB / SQLite]

**Endpoint details:**
- Method: [GET/POST/PUT/DELETE]
- Route: [e.g., /api/v1/users/:id]
- Authentication: [JWT / API key / none]

**Requirements:**
1. Input validation with descriptive error messages (validate params, query, and body)
2. Proper HTTP status codes for every outcome (200, 201, 400, 401, 404, 409, 500)
3. Consistent JSON response envelope: { success, data, error, meta }
4. SQL injection / NoSQL injection prevention
5. Rate limiting headers and pagination support (cursor-based preferred)
6. Request logging with correlation IDs for tracing

Provide the route handler, any middleware needed, and the database query. Include example request/response pairs for the happy path and two error cases.
If you're using an ORM like Prisma or Drizzle, mention it — the generated queries will be much more idiomatic.
4

TypeScript Type Definition from JavaScript

Convert the following JavaScript code to TypeScript by adding complete type definitions.

JavaScript code:
[paste your JS code here]

**Requirements:**
1. Infer types from usage patterns — do not use `any` unless absolutely unavoidable
2. Create named interfaces for all object shapes (not inline types)
3. Use union types and discriminated unions where the code handles multiple cases
4. Add generic type parameters where functions work with variable types
5. Type all function signatures including return types (do not rely on inference for public APIs)
6. Handle nullable values explicitly with optional chaining types (property?: Type) vs. union (Type | null)
7. Export all interfaces and types that other modules would need

Also provide:
- A list of any behavior changes or bugs you discovered during the conversion
- Recommended tsconfig.json strict mode settings for this code
- Any type assertion workarounds needed and why
If the code uses third-party libraries, mention them so ChatGPT can reference the correct @types packages.
5

Array & Object Destructuring Refactor

Refactor the following JavaScript code to use modern ES6+ destructuring patterns throughout.

Code to refactor:
[paste your code here]

**Apply these patterns where they improve readability:**
1. Object destructuring in function parameters (with default values)
2. Array destructuring for swap operations and multi-value returns
3. Nested destructuring for deeply nested API response objects
4. Rest/spread patterns to replace Object.assign and Array.prototype.slice
5. Computed property names where keys are dynamic
6. Shorthand property names where variable names match keys

**Rules:**
- Do NOT destructure when it makes the code harder to read (e.g., more than 3 levels deep)
- Preserve all existing behavior — this is a pure readability refactor
- Add comments explaining any non-obvious destructuring patterns for junior developers

Show a before/after comparison for each significant change.
Ask ChatGPT to also flag any places where destructuring would hurt readability — over-destructuring is a real anti-pattern.
6

Promise Chain to Async/Await Converter

Convert the following Promise-based JavaScript code to use async/await syntax.

Promise-based code:
[paste your .then()/.catch() chains here]

**Conversion rules:**
1. Replace .then() chains with sequential await statements
2. Convert .catch() to try/catch blocks, preserving the same error handling behavior
3. Handle Promise.all() and Promise.race() patterns correctly — keep them as-is but await the result
4. Preserve parallel execution — do NOT accidentally serialize independent promises
5. Convert .finally() to try/catch/finally blocks
6. Handle conditional .then() chains (where a .then() returns early or branches)

**For each conversion, verify:**
- The execution order is identical
- Error propagation behavior is unchanged
- Any returned promises from the original code are still returned

Provide the converted code and flag any places where the original Promise code had subtle behavior that async/await handles differently (e.g., microtask timing).
If your Promise chains use Promise.allSettled(), mention it — the async/await equivalent requires a specific pattern.
7

Event Listener Memory Leak Finder

Audit the following JavaScript code for event listener memory leaks and provide fixes.

Code to audit:
[paste your code here]

**Check for these common leak patterns:**
1. Event listeners added in loops without corresponding removal
2. addEventListener calls without matching removeEventListener in cleanup/unmount
3. Closures in event handlers that capture and retain large objects or DOM references
4. IntersectionObserver, MutationObserver, or ResizeObserver instances never disconnected
5. setInterval or setTimeout references never cleared
6. WebSocket or EventSource connections never closed
7. Detached DOM nodes still referenced by JavaScript variables

**For each leak found:**
- Explain what is being retained and why the garbage collector cannot free it
- Show the exact fix with proper cleanup code
- Estimate the memory impact (negligible, moderate, severe) based on frequency and retained size

Also provide a general checklist I can use to prevent these leaks in future code.
If this is React code, mention it — React has specific patterns (useEffect cleanup) that differ from vanilla JS cleanup.
8

ES6 Module Migration Guide

Help me migrate the following CommonJS (require/module.exports) code to ES6 modules (import/export).

CommonJS code:
[paste your require-based code here]

**Migration requirements:**
1. Convert all require() calls to import statements (named and default imports)
2. Convert module.exports and exports.x to export and export default
3. Handle dynamic require() calls — convert to dynamic import() where needed
4. Update __dirname and __filename usage to use import.meta.url with fileURLToPath
5. Handle circular dependencies that CommonJS resolves but ESM does not
6. Update package.json type field and file extensions if needed (.mjs or "type": "module")

**Also address:**
- Any require() calls inside functions or conditionals (these need dynamic import())
- JSON imports (import assertions or createRequire fallback)
- Node.js built-in module imports (node: protocol prefix)

Provide the migrated code, updated package.json changes, and a list of any breaking changes to watch for.
Specify your Node.js version — ESM support varies significantly between Node 14, 16, 18, and 20+.
9

Jest Unit Test for Async Function

Write comprehensive Jest unit tests for the following async JavaScript function.

Function to test:
[paste your async function here]

**Test coverage requirements:**
1. Happy path — successful execution with valid inputs, verify resolved value
2. Network/API failure — mock fetch or axios to reject, verify error handling
3. Timeout scenarios — simulate slow responses, verify timeout logic fires
4. Retry behavior — if the function retries, verify correct number of attempts and backoff
5. Concurrent calls — verify the function handles being called multiple times simultaneously
6. Input validation — pass null, undefined, empty string, wrong types, boundary values

**Technical requirements:**
- Use jest.mock() for external dependencies (API calls, database, file system)
- Use jest.useFakeTimers() for any time-dependent logic
- Assert on both the return value AND any side effects (function calls, state changes)
- Use descriptive test names: "should [expected behavior] when [condition]"
- Group related tests in describe() blocks
- Include beforeEach/afterEach for setup and cleanup of mocks

Provide the complete test file ready to run with `npx jest`.
If your function uses environment variables, show how to mock them with process.env in beforeEach without polluting other tests.
10

State Management with useReducer

Design a useReducer-based state management pattern for the following React feature.

**Feature:** [describe the feature, e.g., "multi-step checkout form with validation"]

**State shape:**
[describe or paste your current state, e.g., "items array, loading boolean, current step number, form errors object"]

**Actions needed:**
[list the actions, e.g., "add item, remove item, update quantity, set step, validate form, submit order"]

**Requirements:**
1. Define a TypeScript-ready discriminated union type for all actions
2. Implement the reducer with exhaustive action handling (no default fallthrough)
3. Use immer-style immutable updates or explicit spread patterns
4. Create a context provider that exposes state and a dispatch function
5. Build custom hook (useFeatureName) that wraps useContext and provides named action dispatchers instead of raw dispatch
6. Handle async actions (API calls) with a middleware pattern or useEffect side-effect approach

Provide the complete code: types, reducer, context provider, custom hook, and a usage example in a component. Explain when this pattern is better than useState and when to reach for Zustand or Redux instead.
Mention if you need the state to persist across page refreshes — that requires localStorage sync in the provider.
11

Bundle Size Optimization Audit

Audit my JavaScript/TypeScript project for bundle size optimization opportunities.

**Build tool:** [Webpack / Vite / Rollup / esbuild / Next.js]
**Current bundle size:** [e.g., "450KB gzipped main bundle"]
**Framework:** [React / Vue / Svelte / vanilla]

**Project details:**
- Entry points: [list main entry files]
- Key dependencies: [list your largest npm packages]
- Target browsers: [e.g., "last 2 versions, no IE"]

**Analyze and recommend:**
1. Tree-shaking issues — imports that pull in entire libraries (e.g., import _ from 'lodash' vs. import { debounce } from 'lodash-es')
2. Code splitting opportunities — routes, modals, or features that can be lazy-loaded
3. Dependency replacements — lighter alternatives for heavy packages (e.g., date-fns instead of moment, clsx instead of classnames)
4. Dead code elimination — exports that are never imported, polyfills for features you don't need
5. Asset optimization — inline small assets, externalize large ones, use dynamic imports for heavy components
6. Build configuration — source maps, minification, compression settings

For each recommendation, estimate the size reduction and implementation effort (trivial / moderate / significant).
Run 'npx webpack-bundle-analyzer' or 'npx vite-bundle-visualizer' first and paste the output for more targeted advice.
12

Regex Validator Builder

Build a JavaScript regex validation utility for the following use case.

**What to validate:** [e.g., "user-submitted URLs", "custom product SKU format", "cron expressions"]

**Valid examples:**
[list 5-10 strings that should pass]

**Invalid examples:**
[list 5-10 strings that should fail, especially tricky near-misses]

**Requirements:**
1. Write the regex with named capture groups where applicable
2. Add a validation function that returns { valid: boolean, groups: object, errors: string[] }
3. Handle edge cases: leading/trailing whitespace, unicode characters, empty strings
4. Performance: ensure no catastrophic backtracking (ReDoS vulnerability) — avoid nested quantifiers
5. Include a human-readable description of the pattern as a JSDoc comment

**Provide:**
- The regex pattern with line-by-line explanation of each segment
- A reusable validate() function
- A test suite with at least 10 assertions covering valid, invalid, and edge cases
- A note on any inputs that are ambiguous and how you chose to handle them
If your regex needs to work in both browser and Node.js, mention it — lookbehind assertions are not supported in all browsers.

How to Use These Prompts

Copy a prompt, replace the bracketed placeholders with your actual code or project details, and paste it into ChatGPT or any LLM. For best results, include real code snippets rather than vague descriptions — the more context you give, the more precise the output. Use one prompt per conversation to keep responses focused. If you use Prompt Anything Pro, you can save these as reusable templates and trigger them directly on GitHub, CodeSandbox, or any coding platform.

Need More Prompts?

Get personalized AI suggestions for additional prompts tailored to your specific needs.

AI responses are generated independently and may vary

Frequently Asked Questions

Code with AI on Any Platform

Prompt Anything Pro lets you use AI prompts directly on GitHub, VS Code Web, or any code platform.