1. JavaScript

How to create a new Object instance in javascript

Hi Guys, sometimes you face an issue while changing some property in the javascript object, javascript takes a single object instance for one object in memory in your application, when you try to update the property it will update in the memory and the value will be changed all places where the variable is using.

If you wants to create a new instance of your existing object, Here are some following methods you can follow to fix the issue.

Spread syntax

In The below example we used a spread operator to create a new object instance

onDoSomeThing(myObj){
    const newObjectInstance = {...myObj}
    // A new Object instance will be created in memory for object
}    
JavaScript

Using JSON.stringify() and JSON.parse()

Here we are converting the object to a string using the JSON.stringify method, and then parsing to the Object using JSON.parse.

onDoSomeThing(myObj){
    const newObjectInstance = JSON.parse(JSON.stringify(myObj))
      //Sometimes spread object does not work correctly, so this example will diffidently work for creating a new object instance
}    
JavaScript
Comments to: How to create a new Object instance in javascript

    Your email address will not be published. Required fields are marked *

    Attach images - Only PNG, JPG, JPEG and GIF are supported.