Serialization and Deserialization in JavaScript

Serialization and Deserialization in JavaScript

In JavaScript, data often needs to be stored or transferred efficiently. This is where serialization and deserializationcome into play.

What is Serialization?

Serialization is the process of converting a JavaScript object into a structured format(String format).

the most common serialization format is JSON. JSON format is easy for both human and machine to read and write.

const data = {
  name: "Renil",
  age: 20,
  city: "Rajkot"
};

// Convert object -> String (JSON) (serialization)
const serializedData = JSON.stringify(data);
console.log(serializedData);
// Output: {"name":"Renil","age":20,"city":"Rajkot"}

Now, our data is in a JSON string format.

What is Deserialization?

Deserialization is the process of converting serialized data (JSON string) back into a JavaScript object so it can be used in the program.

// Convert JSON string back to a JavaScript object (deserialization)
const deserializedData = JSON.parse(serializedData);
console.log(deserializedData);
// Output: { name: 'Renil', age: 20, city: 'Rajkot' }

Now, our data is reconstructed.


Example why serialization and deserialization is important in js

serialization and deserialization are used for copying objects in JavaScript. When you assign an object to another variable, it creates a reference, not a new copy. To create a deep copy (a completely independent object), serialization and deserialization can be used.

let original = { name: "Renil", age: 20 };
let copy = JSON.parse(JSON.stringify(original));

copy.age = 25;
console.log(original.age); // 30

Here, JSON.stringify() serializes the object into a string, and JSON.parse() deserializes it back into a new object. This ensures copy is independent of original.


Thank you for reading! and don't forget to give feedback and share with your friends!