5

From the MDN documentation:

  • reviver (Optional)

    If a function, prescribes how the value originally produced by parsing is transformed, before being returned.

Its name strikes me as odd. Maybe I’m missing a metaphor here — why would this be called “reviving” an object? Is there any history to such a transformer function being called a “reviver”? Googling reviver +javascript shows that JSON.parse is basically the only place where this term is used.

1
  • 2
    Maybe because it's function used to revive JSON from string? Still it's better naming than parameter or asdlkasflks...
    – Justinas
    Jul 15, 2016 at 8:31

2 Answers 2

5

The idea is that native Javascript objects, like a Number(42), are your "live" objects. When you serialise those into a JSON representation, they're "dried up", or "dumbed down", or whatever you want to call it. To get your fresh live Javascript objects back, you need to "revive" them from their simple text representation.

This becomes more apparent if you use more complex objects:

function Foo(bar) {
    this.bar = bar;
}

Foo.prototype.baz = function () {
    alert(this.bar);
};

var f = Foo(42);
f.baz();
f = JSON.parse(JSON.stringify(f));
f.baz();  // Nope

To get the original object back which has a baz method, you need to do a little more than just parse it. That's the "reviving" part.

2
  • I’ve considered roughly this interpretation, and it makes the most sense to me! I’ll wait for some sort of official citation to roll in, but your example helped solidify my hunch :)
    – Lynn
    Jul 15, 2016 at 8:41
  • 2
    Other languages have similar analogies. See "hydrate" in the Java world: stackoverflow.com/questions/6991135/…
    – deceze
    Jul 15, 2016 at 8:42
1

The parse function is used to create an object from data that has been serialized into a string. By default, all it can do is reconstitute the data into plain objects with a bunch of properties.

Sometimes, you may want to "bring these values back to life" (i.e. revive them) into full-fledged objects with methods, behaviors, etc., or even objects that have a particular type, instead of just the lifeless containers of values that JSON.parse() produces by default.

I would say that's why it's called a reviver.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.