In this article

An empty average can become NaN inside JavaScript and null in JSON. Inspect the value before serialization, then define separate behavior for no observations, invalid samples, and a valid zero.

Find the value before the response was serialized

A chart receives an average of null even though the server calculation never returns null explicitly. One possible cause sits between the arithmetic and the response body: JavaScript has numeric values that JSON.stringify writes as null. An empty list divided by its length produces NaN, and the JSON output loses that distinction. MDN documents this conversion for NaN and infinities. MDN: JSON.stringify value conversion

The following is a deliberately small debugging exercise. It has no database, HTTP framework, or chart library to blame. Save the code blocks in order in one .mjs file and run it with Node. The first assertions establish both observations independently: the calculation produced NaN, and the wire representation contains an explicit null. A successful JSON parse would not reveal which numeric failure occurred earlier.

Observe the arithmetic result and its JSON representation
Codejavascript
import assert from 'node:assert/strict';

function averageBroken(samples) {
  return samples.reduce((total, sample) => total + sample, 0)
    / samples.length;
}

const raw = averageBroken([]);
assert.equal(Number.isNaN(raw), true);
assert.equal(JSON.stringify({ average: raw }), '{"average":null}');
assert.equal(JSON.stringify({ average: Infinity }), '{"average":null}');

    Decide whether no observations is a valid result

    For this endpoint, an empty sample list means no observations yet. Return null for that state on purpose. A nonempty list must contain only finite JavaScript numbers; numeric strings, null values, and nonfinite numbers are invalid input. A valid average of zero stays zero. These are the exercise rules, and they give the debugging work a target beyond making the chart stop complaining.

    That distinction matters to the reader of the response. Zero observations and observations that average to zero support different conclusions. Replacing both with zero creates plausible data rather than fixing the calculation. On the other hand, turning all errors into null hides invalid input behind the legitimate empty state. Preserve the distinction before choosing how an HTTP handler will map rejected input to a status code.

    If the response also includes a count, test that field alongside the average. A count of zero with an intentional null tells a coherent story. A positive count with null may signal a different state that needs its own definition. Do not repair one field while leaving a second field to imply that a valid measurement was computed.

    Number.isFinite is useful here because it does not convert its argument first. A string containing a number is rejected, and so is null. That is different from the global isFinite function. The strict version matches this endpoint contract and avoids quietly broadening accepted input during the repair. MDN: Number.isFinite without coercion

      Validate the samples and the computed result

      Validate the whole list before adding its values. Then handle the empty case explicitly. The final check is also necessary for this implementation: finite inputs can produce a nonfinite intermediate sum. Two Number.MAX_VALUE samples are an example. This helper rejects that calculation instead of letting serialization disguise it as an empty result.

      The overflow rejection is a limitation, not a claim that the mathematical average is undefined. Another numerical method could represent some results this straightforward summation cannot compute. If very large magnitudes are a supported use case, choose that method and test its error properties separately. For this bounded exercise, explicit rejection is preferable to an apparently successful null response.

      An explicit empty state with separate invalid-number failures
      Codejavascript
      function average(samples) {
        if (!Array.isArray(samples)) {
          throw new TypeError('samples must be an array');
        }
        for (const sample of samples) {
          if (!Number.isFinite(sample)) {
            throw new TypeError('samples must contain finite numbers');
          }
        }
        if (samples.length === 0) return null;
      
        const value = samples.reduce((total, sample) => total + sample, 0)
          / samples.length;
        if (!Number.isFinite(value)) {
          throw new RangeError('average calculation overflowed');
        }
        return value;
      }
      

        Check zero, rejected input, and the actual response text

        The expectations below come from the endpoint rules: no observations is null, the average of minus two and two is zero, and two and four average to three. Check those values before serializing them, then check the exact JSON text. Looking only at the parsed body would let a broken empty calculation pass because both NaN and intentional null serialize the same way. MDN: JSON.stringify value conversion

        The negative cases cover a tempting coercion, two explicit nonfinite values, a missing array entry, and overflow. An array hole matters because some array iteration methods skip holes; this implementation uses iteration that observes it as undefined and rejects it. These checks do not prove numerical accuracy for arbitrary magnitudes. They do establish the particular input and representation boundaries that motivated this repair.

        Independent expected values at both sides of serialization
        Codejavascript
        assert.strictEqual(average([]), null);
        assert.strictEqual(average([-2, 2]), 0);
        assert.strictEqual(average([2, 4]), 3);
        assert.equal(JSON.stringify({ average: average([]) }), '{"average":null}');
        assert.equal(JSON.stringify({ average: average([-2, 2]) }), '{"average":0}');
        assert.equal(JSON.stringify({ average: average([2, 4]) }), '{"average":3}');
        
        for (const invalid of [['4'], [null], [NaN], [Infinity], Array(1)]) {
          assert.throws(() => average(invalid), TypeError);
        }
        assert.throws(() => average(null), TypeError);
        assert.throws(() => average([Number.MAX_VALUE, Number.MAX_VALUE]), RangeError);
        
        const averageOrZero = samples => averageBroken(samples) || 0;
        assert.throws(() => assert.strictEqual(averageOrZero([]), null),
          { code: 'ERR_ASSERTION' });
        console.log('average and JSON checks passed');
        

          Ask the assistant to trace one value through each boundary

          Give the assistant the empty input, the pre-serialization observation, the response text, and the intended empty-state rule. Ask where the distinction was lost. A useful answer connects the empty sum, division by zero, and JSON conversion. A patch aimed at the chart component has not explained the server behavior, even if it makes the screen look less broken.

          Review suggested fallback operators carefully. Using result || 0 hides NaN while also treating a real zero as falsy. Using result ?? 0 does not repair NaN because NaN is neither null nor undefined. Neither expression states what no observations means. The executable wrong-alternative check above rejects the first suggestion without relying on the assistant to critique its own prose.

          In an application, place a focused regression where the response object is created, and keep a calculation test for its input policy. If logging is available, record enough context to distinguish an empty list from rejected input without dumping sensitive observations. The illustrative helper throws errors; translating those errors into your API error contract is a separate caller responsibility.

            Common questions when a number becomes JSON null

            Should a custom JSON replacer throw on every nonfinite value? It can provide an additional serialization check, but it cannot decide whether an empty sample list should produce null. Keep the business rule where the calculation is defined. A response-level safeguard is useful only if its failures are handled and its coverage is understood.

            Can a client tell whether null came from NaN? Not from this JSON value alone. The server must preserve or reject that distinction before serialization. Does finite mean accurate? No. Number.isFinite checks type and finiteness, not rounding error, measurement quality, or numerical stability. Use it to enforce this boundary, and choose further checks from the actual calculation requirements.

              Sources & editorial notes

              This article was authored with AI using primary-source research and an automated technical review. It has not been reviewed by a human. Code examples are illustrative; run and verify them in your own environment.

              1. MDN: JSON.stringify value conversion

                Checked November 30, 2026. Documents serialization of NaN and infinities as null; this is reference behavior, not a new announcement.

              2. MDN: Number.isFinite without coercion

                Checked November 30, 2026. Documents finite-number checks without coercing strings or null into numbers.

              nrml promotion

              Put the reading into practice

              Work through an existing repository, review AI suggestions, and test the decisions behind your changes.

              Explore practice problems