Refactoring Legacy JavaScript with Claude 3.5 Sonnet
I use Claude 3.5 Sonnet to refactor legacy JavaScript in small, reviewable slices while protecting hidden dependencies, old runtimes, and error behavior.


The file had been sitting in the uncomfortable category of code that worked, but only because everyone already knew which parts not to touch. It was a roughly 600-line JavaScript utility file with shared state, old calling patterns, and error messages that other parts of the project quietly depended on. I wanted to make it easier to maintain. I did not want to discover that my cleanup had changed the application two weeks later.
That was where Claude 3.5 Sonnet became useful. Not as an automatic modernization button, and not as a replacement for running the code. I used it more like a second developer who could read a large function without getting bored, provided I gave it a narrow job and checked every suggestion.
The first mistake was asking for a rewrite
My first instinct was the predictable one: give Claude the file and ask it to rewrite the old JavaScript using modern patterns. The response was technically attractive. Some nested conditionals became easier to read, repeated checks were consolidated, and parts of the control flow looked much cleaner.
It also made me uncomfortable almost immediately. The proposed changes crossed too many boundaries at once. A helper function had been renamed, a return path had been simplified, and a piece of state that looked local was being passed around differently. I could have spent a long time reviewing that output, but I would have been reviewing a new program instead of a refactor.
I stopped that pass. The problem was not that Claude had produced bad JavaScript. The problem was that I had asked for elegance before documenting the contract. Legacy code often contains rules that are not written down anywhere. The old error text may be checked by a caller. A null value may be intentional. A global object may be the only way a separate module knows which environment it is running in.
I made Claude inspect the code before changing it
The next prompt was deliberately boring. I gave Claude one function at a time and asked it to describe the function’s inputs, return shape, mutation points, external dependencies, and possible callers. I also asked for a risk list and told it not to produce replacement code yet.
That changed the quality of the work. While mapping the utility file, Claude pointed out that several functions read from a shared global configuration object. It was not passed as an argument, and the reference was easy to mistake for a harmless convenience. In reality, the object was initialized elsewhere and changed between different execution paths.
I knew the global existed, but I had not connected it to all of the functions that depended on its current value. If I had started with a broad rewrite, I probably would have turned that hidden dependency into a cleaner-looking bug. The analysis did not solve the problem by itself. It gave me a map of where I needed to be careful.
I then wrote the constraints directly into each task. Keep the existing return shape. Support Node 14. Do not change error messages. Do not alter the order of side effects. Show the changed section and explain any behavior that might differ. Those instructions were less exciting than asking for modern JavaScript, but they made the output much easier to review.
Small diffs made the model useful
After the inspection pass, I worked in slices. One function, one requested change, one test or manual check. I avoided sending the entire file unless Claude needed surrounding context to understand a dependency. Usually I included the target function, its nearby helpers, and a short description of the caller.
One slice removed repeated parsing logic. Another separated validation from the operation that mutated shared state. In both cases, I asked Claude to preserve the existing behavior first and suggest a more ambitious redesign separately. That distinction mattered. The safe refactor could be reviewed against the old code. The redesign could wait until I had evidence that it was needed.
Claude was particularly helpful at explaining awkward sections in plain language. It could trace a value through several branches and identify that a function returned an object in one path but an empty array in another. I still had to decide whether that inconsistency was a bug. The model could highlight the mismatch; it could not know whether some caller relied on it.
My review loop was not sophisticated. I ran the existing checks, exercised the affected path manually, and inspected the diff line by line. When the project had no useful test for a behavior, I wrote down the old result before changing the code and compared it afterward. That small habit caught more than one accidental change to a fallback value.
The optional chaining detour
The most annoying issue came from a suggestion that looked completely harmless. Claude used optional chaining while simplifying a nested property access. The syntax was readable and supported by modern Node versions, but this project still needed to run on Node 14 through an older build setup.
The Babel configuration did not transpile that syntax for the path I was testing. The result was not a subtle behavioral difference. The code failed before the relevant function could run, which made the debugging detour especially irritating because the refactor itself was logically correct.
I removed the optional chaining and used the more verbose checks already common in the codebase. That was not the prettier choice, but it matched the runtime contract. I also added runtime and build configuration to the prompt from that point onward. Claude is very good at writing code for the environment described in front of it. If the environment is missing from the description, it will often assume a newer one.
There were smaller corrections too. A proposed early return changed when a logging call ran. A cleaned-up error branch used a different message. A variable rename made sense locally but made the diff harder to compare with existing issue reports. None of these were dramatic failures. They were reminders that a refactor is judged by preserved behavior, not by how modern the final syntax appears.
What changed in my workflow
I did not finish with a completely rewritten utility file, and that was the right outcome. The code became easier to follow in several areas, but the changes remained narrow enough that I could explain them. Shared mutation was more visible. Repeated logic was reduced. A few functions had clearer boundaries without pretending that the whole module was now clean.
The bigger improvement was in my workflow. I stopped asking Claude to be a maintainer with unlimited authority. I gave it a role for each pass: map dependencies, identify risks, propose one compatible change, or explain a diff. That made the conversation less impressive but much more useful.
The speed came from shorter review loops, not from skipping review. Claude reduced the time needed to understand a dense function and offered alternatives quickly. I supplied the missing context, tested the result, and rejected anything that violated the old contract.
My takeaway is simple: legacy code needs evidence before elegance. Claude 3.5 Sonnet can make the evidence-gathering and comparison work faster, but it cannot decide which undocumented behavior is safe to remove. For that part, I still need the diff, the runtime, the caller, and a willingness to stop when a clean rewrite starts looking too easy.

Rafiqul Islam Rabbi
Full-Stack & E-Commerce Architect building high-converting Shopify stores, WordPress platforms, and Next.js web applications.