Javascript Serializer

Serialize Javascript variables


Javascript Serializer can convert almost any object in a browser to a string representation of itself. It's useful when generating error logs when stack traces are not enough.

What This Tutorial Covers

What This Tutorial Covers
  1. Using Javascript Serializer
  2. What It Can't Serialize

What You Need For This Tutorial

What You Need For This Tutorial

A browser

Using Javascript Serializer

Javascript Serializer

To use Javascript Serializer, import the following two files:

<script src=""><script>
<script src=""><script>

Using the serialize function couldn't be easier. You just pass the variable you want serialized into the function and it returns a string representation of the variable.

var myObject = { 'example' : 'object' };
var serializedObject = serialize(myObject);

// you can deserialize the string as well:
var deserializedObject = deserialize(serializedObject);

Caveats. What It Won't Serialize

In order to serialize an object, you need one of three things:

  1. If it's a primitive value, simple, you just store it as a string. To keep typing, you store primitive strings with single quotes around them.
  2. If it's an object, hopefully there is a reflection method that gives you a string that can help you reconstruct it.
  3. If it doesn't have reflection, but it's iterable, you can copy the object to a string by iterating through it.
  4. If it's a DOM Node, you can use the XMLSerialize.serializeToString & DOMParser.parseFromString

You can see below, how the serialize function works, looking for one of those four conditions. However, it uses an additional trick. If it detects a native object (which is a built in object attached to the window), it will try to find it's name on the window. Since those native objects always exist on the window, if we can figure out the name, we can just leave it there, since it will resolve to the native object when deserialized. You might think that should be easy, but there is no way of determining the name of a variable using javascript. For that matter, the variable name may have been changed and what we really want, is it's original property name on the window.

So what can't it serialize? An object that doesn't meet one of those 4 conditions and isn't a native object. Thus, a variable that is not a primitive, doesn't have a useful reflection method, isn't iterable, and isn't a Node object. An example of that is a Promise.


I hope you found that interesting if not useful.