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.

Community
  • 1
  • 1
Lynn
  • 8,876
  • 38
  • 66
  • 2
    Maybe because it's function used to `revive` JSON from string? Still it's better naming than `parameter` or `asdlkasflks`... – Justinas Jul 15 '16 at 08:31

2 Answers2

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.

deceze
  • 471,072
  • 76
  • 664
  • 811
  • 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 '16 at 08:41
  • 2
    Other languages have similar analogies. See "hydrate" in the Java world: http://stackoverflow.com/questions/6991135/what-does-it-mean-to-hydrate-an-object – deceze Jul 15 '16 at 08: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.

JLRishe
  • 90,548
  • 14
  • 117
  • 150