javascript pass by value 1

javascript pass by value

function func(obj) {
  obj = JSON.parse(JSON.stringify(obj)); //If too slow, replace with other method of deep cloning
  obj.a += 10;
  return obj.a;

var myObj = {a: 5};
func(myObj); //Returns 15 and myObj.a is still 5

Here is what the above code is Doing:
1. The function func() takes an object as an argument.
2. The object is cloned using JSON.parse(JSON.stringify(obj)).
3. The cloned object is modified.
4. The cloned object is returned.
5. The original object is not modified.

Similar Posts