CodeNestでAIに質問し、修正をテストする:文字列の合計が「01020」になる例 #JavaScript - Qiita
@CodeNest_media
inHatch-IT Co., Ltd.

Ask AI a question in CodeNest and test the fix: An example where the sum of strings comes out as “01020”

  • JavaScript
  • Node.js
  • debug
  • AI
0
TAG39@@
Last updated at 2026-11-12Posted at 2026-11-12
When you apply the fix suggested by the AI, a different error appears this time. If you paste in additional logs, you get a different fix than before. After a few back-and-forth exchanges, you can no longer even trace which change was necessary yourself.

To organize this kind of back-and-forth, the first thing you want to prepare is **a runnable example that says, “For this input, I want this result.”** Rather than merely adding information, make it a form in which you can judge for yourself whether the answer is correct.

Using a bug in which strings are concatenated when you intend to add numbers as the subject, rewrite an ambiguous question into a reproducible one. The goal is to put together the execution environment, expected result, actual result, and reproduction steps so that you can determine whether to accept the returned fix using the same input.

This is intended for people who can write JavaScript functions. On November 12, 2026, I reran the code shown in the article on macOS and Node.js v26.8.1 and confirmed the output below. This is not an experiment comparing the quality of AI responses based on the wording of the question; it covers how to create the evidence and acceptance criteria to accompany a question.

Break down “the sum is wrong” into the type and value

Suppose you intend to add ['10', '20'] read from a CSV and write reduce((a, b) => a + b, 0). You expect the number 30, but the result is the string '01020'.

First, adding the string '10' to 0 produces '010', and then '20' is concatenated as well. Converting to Number after summing only yields 1020, not 30.

By distinguishing not just “the value is different,” but “it should be a number, but it is a string,” you can see where the fix needs to be made. The conversion should occur before adding each element, not after summing.

For this time, let's define the specification as follows.

  • The input is an array of strings representing numbers. For ['10', '20'], return the number 30.
  • Reject empty strings, strings containing only whitespace, strings that cannot be converted to numbers, and infinities.
  • Exclude currency-specific format validation and exact decimal calculations from the scope of this exercise.

The third point is also important. If it remains unclear what you are building, you cannot determine whether a fix is necessary even when the AI independently adds a “helpful conversion.”

Make it an example that reproduces the same failure without passing real data

Save the following as question.mjs in an empty folder, and run node question.mjs. No additional packages are needed. The first half reproduces the bug, and the second half contains the fix and tests.

question.mjs
import assert from 'node:assert/strict'; const input = ['10', '20']; const wrong = input.reduce((a, b) => a + b, 0); console.log(`before: ${JSON.stringify(wrong)} (${typeof wrong})`); function sum(values) {return values.reduce((total, raw) => { if (typeof raw !== 'string' || raw.trim() === '') throw new TypeError('invalid amount'); const n = Number(raw); if (!Number.isFinite(n)) throw new TypeError('invalid amount'); return total + n; }, 0); }assert.equal(sum(input), 30); for (const bad of ['', ' ', '10x', 'Infinity']) assert.throws(() => sum([bad]), TypeError); console.log(`after: ${sum(input)} (${typeof sum(input)}); 4 invalid inputs rejected`);

The execution results are as follows:

$ node question.mjs before: "01020" (string) after: 30 (number); 4 invalid inputs rejected

The exit code was 0 (in bash, you can check by running node question.mjs; echo "exit=$?").

Here, we were able to reproduce the string-concatenation failure using only the fictional 10 and 20. Adding customer names, internal price lists, or API keys would not make this bug any easier to explain.

When replacing real data, it is necessary not only to remove sensitive information but also to preserve the properties that cause failures. This time, if '10' were simply changed to the number 10, the failure could no longer be reproduced in the code used for the question. Running it once again after anonymization ensures that this change is not overlooked.

A supplementary exercise to incorporate into CodeNest learning

As a technical article about operating CodeNest by Hatch IT, this article presents an example of connecting the code discussed so far with learning. On the web interface checked on November 12, 2026, the JavaScript course “Transform Data with Array Methods” included “Aggregate Values with reduce.” The example in this article is a supplementary exercise created to confirm understanding of that material. It is not an excerpt from existing course materials or an actual AI response.

The entry point checked was “My Courses” → “JavaScript” → “Start from the Beginning” for the target unit. Learning to write code requires the dedicated CodeNest Editor; it cannot be done solely from the web course interface. This time, we opened the Editor and asked a question in the “AI Tutor” chat on the right, providing the reproduction code, expected value, and inputs to be rejected.

The AI Tutor explained that the initial 0 + '10' results in string concatenation, and that each input should be validated and converted to a number before addition, and presented a correction using trim() and Number.isFinite(). This was an observation from a single exchange in this instance; it was not an experiment comparing response quality.

We then checked the Node.js version in the “Terminal” within the Editor and tested the same correction process as in this article using node:assert/strict. The valid input produced the number 30, while four types of invalid input—an empty string, a whitespace-only string, '10x', and 'Infinity'—raised exceptions. The displayed output was as follows:

Node v26.8.1 before: "01020" string after: 30 number PASS: 30 and 4 rejected inputs

Here, the test included in the AI response was written to output OK/NG to the log. Because the process itself was written to terminate successfully even when NG appeared in the log, this article instead uses assert, which raises an exception when it fails. Reading exactly how the response's test signals failure is essential to deciding whether to accept the correction.

If using this example for learning, proceed in the following order.

  1. First, without looking at the corrected version, predict the result using only ['10', '20'] and reduce((a, b) => a + b, 0). Run it and record the predicted type and value.
  2. When asking the AI, provide your execution environment, code, and output along with the sample question below. Ask not only for “code that works,” but also for an explanation of what the initial 0 + '10' becomes.
  3. Try the proposed correction with the same inputs. In addition to confirming that it produces 30, verify that it rejects an empty string, a whitespace-only string, '10x', and 'Infinity'.
  4. Finally, close the code and explain in your own words why converting to Number after the summation does not fix the problem.

The goal of this flow is not “the AI answered,” but “you tested the correction with the same inputs and were able to explain the order of conversion.” This does not guarantee that the response content or learning outcomes will necessarily be the same.

Building a question directly from the information you were able to reproduce

“The total is wrong. Please fix it” does not indicate the input format or the correct result. In this case, it can be written as follows.

I am running the saved question.mjs as `node question.mjs` on macOS with Node.js v26.8.1. The input is an array of strings originating from CSV. I want to total `['10', '20']` to the numeric value 30, but `reduce((a, b) => a + b, 0)` produces the string `'01020'`. I am reproducing the issue with the minimal code shown below. I want to reject empty strings, whitespace-only strings, strings that cannot be converted to a number, and Infinity. Please explain the cause and the minimal fix, and show how to verify the fix using this input. I would like to avoid adding a new library.

For this question, include the code and output from the reproduction you ran yourself. Rather than treating the corrected version in the article verbatim as “the AI’s answer,” provide the facts you were able to confirm when asking the question.

Each piece of information has a role.

Information to retain Information that reduces speculation by the respondent
Environment and execution command Where and how it was run
Specific input Whether the same failure can be reproduced
Expected type and value What constitutes a completed fix
Actual type and value Where it diverged from the expectation
Inputs to reject and constraints on the change Things that must not be broken during the fix

If the code is long, do not paste all of it from the beginning; retain only the parts that affect the result. If deleting something makes the issue impossible to reproduce, the processing or configuration removed immediately before it is a clue.

Once you receive an answer, verify it with the same input rather than being persuaded by the explanation.

This corrected version rejects empty strings first, converts each string with Number, and sums only finite numbers. It checks for empty strings first because `Number('')` is 0. Using parseInt to read only the leading portion would not be sufficient either. Under the current specification, `'10x'` is to be rejected.

Also test the answer you give yourself using the original `['10', '20']` unchanged. Furthermore, check that empty strings and invalid inputs have not silently become 0. If only valid values are accepted while invalid inputs are glossed over, the acceptance criteria have not been met.

This code is an exercise in handling finite values that can be interpreted as JavaScript Numbers. Number ignores surrounding whitespace and interprets prefixes such as `0x` and exponential notation as numbers, so independent verification accepted `' 10 '` as 10, `'0x10'` as 16, `'1e3'` as 1000, and `'-5'` as -5. The sum of `['0.1', '0.2']` is also 0.30000000000000004. If you want to reject these when they are used as CSV monetary amounts, that is a separate specification concerning “the format of strings to accept.” For example, define conditions such as allowing only digits with a regular expression, and then expand the validation.The handling of negative numbers and the upper limit on the total are the same as well.

If the response is still off target, where in the question should you go back to?

What went wrong Additional information and points to review
It cannot be reproduced in the other party’s environment Run the minimal code yourself in a new folder and compare the versions and execution methods
A complete rewrite is suggested Clearly state the scope that may be changed and the input and output that should be preserved
The first example is fixed, but another input breaks it Add the broken input as a new acceptance criterion (for example, if you want to reject '0x10', write that expectation in the question)
It no longer reproduces after being anonymized Check one by one any properties changed by the substitution, such as type, null values, order, and count
Although the inquiry is about a connection failure, a logic fix is returned Add information about the stage of the failure, such as when it occurred, the HTTP status, and the type of connection destination

The essence of asking a question is not merely writing something for the other person to fix. It is also aligning the observed facts with your expectations and creating a state in which you can evaluate the fix yourself. Before asking your next question, write the input, the expectation, and the actual result on separate lines. Those three lines will serve as a reference point that you will not lose even as the exchange continues.

References (primary sources)

For those who want to be able to resolve similar stumbling blocks in their own code as well.View CodeNest’s learning content (Operated by Hatch IT)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
Sign upLogin