Skip to content

serialize(-0) returns "0" - negative zero is lost on round-trip #234

Open

Description

@philppplik

Version: 7.1.2 (latest on npm)

serialize-javascript goes out of its way to preserve the numeric values JSON can't represent - NaN, Infinity, and -Infinity are all emitted as placeholders so they round-trip correctly. -0 falls through the same JSON.stringify path and comes back as plain 0, so a serialized-then-evaluated value is no longer Object.is-equal to the original.

Repro:

const serialize = require('serialize-javascript');

const s = serialize(-0);
console.log(s);                          // "0"
console.log(Object.is(eval('(' + s + ')'), -0)); // false

console.log(serialize({ startTime: -0 })); // {"startTime":0}

For comparison, the sibling edge cases do round-trip:

Object.is(eval(serialize(NaN)), NaN) // ...evaluates NaN via placeholder
eval(serialize(Infinity))            // Infinity
eval(serialize(-Infinity))           // -Infinity

Why it matters: -0 is a real, observable value in JS (Object.is(-0, 0) === false, 1 / -0 === -Infinity). Code that round-trips state through serialize-javascript (worker messaging, SSR state injection, template embedding - the library's main use cases) silently loses the sign. A consumer computing 1 / value after deserialization gets Infinity instead of -Infinity.

Possible fix: in the number branch, detect Object.is(obj, -0) (or obj === 0 && 1 / obj === -Infinity) and emit a placeholder alongside the existing NaN/Infinity/-Infinity ones.

Happy to take a look at a PR if that would help.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions