Sanjith Sanjith - 5 months ago 19
Javascript Question

Instance of object getting changed in javascript

I have following global variables.

var name1 = "James";
var nameObj = { name: name1 };


In button click, I am changing the value in variable name1. While changing the value in name1 instance of the variable is getting changed. Find my code below.



var name1 = "James";
var nameObj = {
name: name1
};

function point() {
name1 = "James"
if (nameObj.name !== name1) {
alert("instance changed");
}
}

<button onclick="point()">Click</button>





Is there anyway to change the value in name1 without changing its instance?

Answer Source

No, because strings are immutable. Here's a reference from MDN web docs:

Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string.