AI Prompts for ChatGPT for JavaScript

20 tested prompts across 4 stages. Works with ChatGPT, Claude, and Gemini.

AI Prompts for ChatGPT for JavaScript
Scroll to explore

Write modern JavaScript and TypeScript faster, debug complex async issues, build React components, and architect Node.js applications using ChatGPT prompts designed for web developers. Built across 4 distinct stages covering Foundation: Modern JavaScript Patterns, React: Components and State Management, Node.js: Backend and Server-Side and more, this guide gives you one tested prompt per step so you never have to write from scratch or guess what the AI needs. The prompts work in ChatGPT, Claude, and Gemini and are designed to get usable output on the first try.

Stage 1

Foundation: Modern JavaScript Patterns

Modern JavaScript has evolved dramatically. These prompts produce ES2022+ code that uses the language's current best practices rather than legacy patterns.

Modern JS Refactor

Refactor this JavaScript code to use modern ES2022+ features: [PASTE CODE]. Apply where appropriate: optional chaining (?.), nullish coalescing (??), logical assignment operators (&&=, ||=, ??=), Array.at(), Object.entries/fromEntries for transformations, structuredClone for deep copying, and top-level await if this is a module. Replace var with const/let appropriately. Explain each modernization and why it improves the code. Flag any changes that would break older browser support if the code runs in the browser.

Foundation: Modern JavaScript Patterns

Async/Await Pattern

Write a JavaScript function that [DESCRIBE ASYNC OPERATION: FETCH DATA FROM API, READ FILES, QUERY DATABASE]. Use async/await with proper error handling. Include: (1) try/catch with specific error handling for different failure modes (network error vs. invalid response vs. auth error), (2) Promise.all() or Promise.allSettled() for concurrent operations if applicable, (3) abort controller for cancellable requests, (4) retry logic with exponential backoff for transient failures, (5) JSDoc type annotations. Show the anti-pattern (callback hell or unhandled rejections) alongside the clean version.

Foundation: Modern JavaScript Patterns

Array and Object Utilities

Write a set of JavaScript utility functions for [DESCRIBE USE CASE: TRANSFORMING API RESPONSES, PROCESSING USER DATA, HANDLING CONFIGURATION OBJECTS]. For each utility: (1) use modern array methods (flatMap, findIndex, every, some, reduce) over manual loops, (2) handle edge cases (empty arrays, null/undefined values, missing properties), (3) write it as a pure function with no side effects, (4) include JSDoc with types, (5) add a usage example. Also add a TypeScript generic version of any function that would benefit from type parameters.

Foundation: Modern JavaScript Patterns

Module Pattern with ES Modules

Design a JavaScript module for [DESCRIBE THE MODULE'S RESPONSIBILITY: E.G., AUTHENTICATION STATE MANAGEMENT, API CLIENT, FORM VALIDATION, EVENT HANDLING]. Use ES module syntax (import/export). The module should: export a clean public API using named exports, keep implementation details private, handle initialization and cleanup, be tree-shakeable (avoid exporting an object with all methods), and include a default export for the main interface if appropriate. Show the module structure and 3 example imports from consuming files.

Foundation: Modern JavaScript Patterns

Event Handling Pattern

Write a clean JavaScript event handling system for [DESCRIBE THE USE CASE: DOM EVENT DELEGATION, CUSTOM EVENT BUS, COMPONENT COMMUNICATION, USER INTERACTION TRACKING]. Requirements: (1) proper cleanup/removal of listeners to prevent memory leaks, (2) event delegation pattern for dynamic elements if DOM-based, (3) throttle or debounce for high-frequency events (resize, scroll, input), (4) typed custom events with CustomEvent, (5) error handling so one bad handler does not crash others. Show how to add, trigger, and remove listeners.

Foundation: Modern JavaScript Patterns

Stage 2

React: Components and State Management

React development has shifted to hooks and functional components. These prompts produce modern React patterns using current best practices.

React Component with Hooks

Write a React component for [DESCRIBE WHAT THE COMPONENT DOES: A DATA TABLE WITH SORTING AND FILTERING, AN INFINITE SCROLL LIST, A FORM WITH VALIDATION, A MODAL DIALOG]. Requirements: (1) functional component with TypeScript props interface, (2) appropriate hooks (useState, useEffect, useCallback, useMemo, useRef), (3) memoization where beneficial (React.memo, useMemo, useCallback), (4) loading, error, and empty states, (5) accessibility attributes (ARIA labels, keyboard navigation), (6) clean dependency arrays in useEffect. Add JSDoc for the props interface.

React: Components and State Management

Custom Hook

Write a custom React hook for [DESCRIBE THE SHARED LOGIC: FETCHING DATA FROM AN API, MANAGING FORM STATE, HANDLING INTERSECTION OBSERVER, SYNCING WITH LOCALSTORAGE, MANAGING A TIMER]. The hook should: start with "use" prefix, return a clean API with the state and handlers the consumer needs, handle cleanup in useEffect, avoid exposing internal implementation details, work correctly with React Strict Mode (double-invocation), and include TypeScript generics if applicable. Show the hook definition and 2-3 usage examples in components.

React: Components and State Management

State Management with useReducer

Refactor this component that uses multiple useState calls to use useReducer: [PASTE COMPONENT OR DESCRIBE THE STATE SHAPE]. Design: (1) a typed State interface, (2) a discriminated union Action type covering all state transitions, (3) a pure reducer function, (4) action creators for each action type, (5) any async operations handled with useEffect + dispatch (not in the reducer), (6) the refactored component showing how dispatch replaces setState calls. Explain when useReducer is better than useState and when Context should be added.

React: Components and State Management

React Context with Provider

Set up a React Context for sharing [DESCRIBE STATE: USER AUTHENTICATION, THEME PREFERENCES, SHOPPING CART, FEATURE FLAGS] across the component tree. Create: (1) the typed Context definition with a sensible default, (2) a Provider component that manages the actual state, (3) a custom useContext hook with a null check that throws a helpful error if used outside the Provider, (4) TypeScript types for everything, (5) an example of nesting multiple providers, (6) optimization to prevent unnecessary re-renders. Also note when to use Context vs. a state management library.

React: Components and State Management

React Performance Optimization

Analyze and optimize this React component or component tree for performance: [PASTE COMPONENT OR DESCRIBE THE PERFORMANCE PROBLEM]. Identify: (1) unnecessary re-renders and their causes, (2) where React.memo, useMemo, and useCallback would help (with explanation of each), (3) any expensive computations that should be moved outside the render cycle, (4) list rendering optimizations (stable keys, virtualization if applicable), (5) any anti-patterns that are invalidating memoization. Provide the optimized version and explain how to measure the improvement with React DevTools Profiler.

React: Components and State Management

Stage 3

Node.js: Backend and Server-Side

Node.js has matured into a solid backend platform. These prompts cover API development, middleware, and common server patterns using current Node.js conventions.

Express API Endpoint

Write an Express.js route handler for [DESCRIBE THE ENDPOINT: GET/POST/PUT/DELETE, WHAT IT DOES, WHAT DATA IT RECEIVES AND RETURNS]. Include: (1) input validation using zod or express-validator, (2) proper HTTP status codes for success and each error case, (3) async error handling with a try/catch that passes to next(err), (4) middleware for authentication check if needed, (5) rate limiting annotation, (6) JSDoc or OpenAPI comment for the endpoint. Also write a corresponding test using supertest.

Node.js: Backend and Server-Side

Middleware Pattern

Write a custom Express middleware for [DESCRIBE PURPOSE: REQUEST LOGGING, AUTHENTICATION VERIFICATION, REQUEST VALIDATION, RATE LIMITING, CORS HANDLING, RESPONSE COMPRESSION]. The middleware should: follow the (req, res, next) signature, handle errors by calling next(error), not block the event loop, add TypeScript extension to the Request interface if adding custom properties, and be composable with other middleware. Include mounting examples and show how to apply it globally vs. per-route.

Node.js: Backend and Server-Side

Database Query Layer

Write a database access layer for [DESCRIBE: WHAT DATA ENTITY, WHAT OPERATIONS NEEDED: CRUD, SEARCH, PAGINATION, AGGREGATION]. Use [SPECIFY ORM/DRIVER: PRISMA / DRIZZLE / PG / MONGOOSE / KNEX]. Include: (1) typed function for each operation, (2) parameterized queries (never string interpolation), (3) transaction support for operations that need atomicity, (4) pagination using cursor-based or offset approach, (5) error handling that wraps database errors in application-level errors, (6) connection pooling configuration. No raw SQL string interpolation anywhere.

Node.js: Backend and Server-Side

WebSocket Handler

Write a WebSocket server implementation for [DESCRIBE USE CASE: REAL-TIME CHAT, LIVE DASHBOARD, COLLABORATIVE EDITING, GAME STATE SYNC]. Use the ws library or Socket.io (specify which). Include: (1) connection and disconnection handling, (2) message parsing and validation, (3) broadcasting to all clients or specific rooms, (4) heartbeat/ping-pong for connection health, (5) reconnection logic on the client side, (6) graceful shutdown that closes all connections, and (7) basic authentication on connection. Show both server and client code.

Node.js: Backend and Server-Side

Background Job / Queue

Set up a background job processor for [DESCRIBE THE JOB: SENDING EMAILS, PROCESSING UPLOADED FILES, CALLING SLOW EXTERNAL APIS, GENERATING REPORTS]. Use BullMQ or Bull (or specify another queue library). Include: (1) job producer that adds jobs to the queue with appropriate options (retry, delay, priority), (2) worker that processes jobs with proper error handling, (3) dead letter queue handling for repeatedly failing jobs, (4) job progress reporting, (5) rate limiting for external API calls, (6) graceful shutdown that waits for current jobs to complete. Show the Redis connection setup.

Node.js: Backend and Server-Side

Stage 4

Tooling: Testing, TypeScript, and Debugging

Modern JavaScript development requires strong tooling. These prompts cover the TypeScript patterns, testing setups, and debugging techniques that professional JS developers use daily.

TypeScript Type Utilities

Help me solve this TypeScript type problem: [DESCRIBE WHAT TYPES YOU HAVE AND WHAT TYPE YOU ARE TRYING TO EXPRESS]. Use TypeScript utility types (Partial, Required, Pick, Omit, Record, Extract, Exclude, ReturnType, Parameters, Awaited) and if needed, conditional types and template literal types. Show: (1) the solution using the simplest possible TypeScript features, (2) the type in action with example values that do and do not satisfy it, (3) any edge cases the type does not handle and why. Explain the type at a level appropriate for a senior developer learning advanced TypeScript.

Tooling: Testing, TypeScript, and Debugging

Jest Test with Mocking

Write a Jest test suite for this JavaScript/TypeScript module: [PASTE CODE]. The tests should: (1) mock external dependencies (modules, API calls, database) using jest.mock() and jest.spyOn(), (2) test happy path behavior, (3) test all error conditions including thrown errors and rejected promises, (4) use beforeEach/afterEach for setup and cleanup, (5) assert on mock calls (toHaveBeenCalledWith, toHaveBeenCalledTimes), (6) test async code properly with async/await. Also explain how to run these tests and check coverage.

Tooling: Testing, TypeScript, and Debugging

ESLint Config Explanation

I have this ESLint error/warning in my JavaScript or TypeScript code: [DESCRIBE THE RULE NAME AND THE CODE IT IS FLAGGING]. Explain: (1) why this ESLint rule exists and what problem it prevents, (2) whether this is a rule I should fix or disable in this specific case, (3) the correct fix if I should fix it, (4) how to disable it for just this line or file if there is a legitimate reason, and (5) any related rules I should also check. Do not just suppress the error; explain what is actually wrong.

Tooling: Testing, TypeScript, and Debugging

Bundle Size Optimization

Help me reduce the JavaScript bundle size for my web application. I am using: [DESCRIBE: WEBPACK/VITE/ROLLUP, REACT/VUE/VANILLA, ANY LARGE LIBRARIES]. My current bundle size is approximately [X] KB. Analyze: (1) which import patterns are preventing tree-shaking, (2) which large libraries have lighter alternatives, (3) how to implement code splitting for routes or heavy components, (4) how to configure my bundler for optimal production output, (5) what lazy loading opportunities exist in my code: [PASTE RELEVANT IMPORT SECTIONS]. Provide before/after code examples for each optimization.

Tooling: Testing, TypeScript, and Debugging

Chrome DevTools Debug Strategy

I am debugging a JavaScript issue in the browser: [DESCRIBE THE BUG: WHAT IS HAPPENING, WHAT YOU EXPECTED, ANY ERROR MESSAGES, WHAT YOU HAVE ALREADY TRIED]. Walk me through a systematic debugging strategy using Chrome DevTools: (1) which DevTools panels to use and in what order, (2) how to set up the right breakpoints for this specific type of bug, (3) what to look for in the Call Stack, Scope, and Watch panels, (4) how to use the Console to run diagnostic code while paused, and (5) how to record and analyze performance if the issue is a slowdown or jank. Write the debugging steps as a checklist.

Tooling: Testing, TypeScript, and Debugging

Frequently asked questions

How do I get ChatGPT to write modern JavaScript instead of outdated patterns?+

Explicitly specify the target environment and ES version in your prompt: "Write modern ES2022+ JavaScript for Node.js 20" or "Write React 18 functional components with TypeScript." Without this context, ChatGPT sometimes defaults to older patterns like var declarations, callback-style async, or class components. Always specify your target environment.

Can ChatGPT help me with TypeScript type errors?+

Yes, and it is particularly effective when you paste the exact TypeScript error message, the relevant type definitions, and the code causing the error. TypeScript type errors have specific messages that contain the key information for diagnosis. Ask ChatGPT to explain the error first, then fix it, rather than asking it to fix a type error without understanding what went wrong.

What React hooks questions is ChatGPT best at answering?+

ChatGPT is excellent at explaining hook rules, diagnosing stale closure bugs in useEffect, recommending when to use useCallback and useMemo, and designing custom hooks. It is less reliable for cutting-edge features or very recent React API changes. Always check the React documentation for any hook behavior you are uncertain about.

How do I use ChatGPT for JavaScript debugging without sharing my whole codebase?+

You rarely need to. Paste only the minimal reproducing case: the function or component with the bug, the error message and traceback, any relevant type definitions, and a description of what input triggers the bug. Irrelevant surrounding code makes it harder for ChatGPT to focus on the actual problem.

Is ChatGPT good at Node.js backend development?+

ChatGPT is solid for common Node.js patterns: Express routes, middleware, database queries, and REST API design. It is less reliable for performance optimization at scale, complex event loop timing issues, and very new Node.js APIs. For authentication and security code specifically, always review the output carefully and compare against current OWASP guidelines.