Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

when I pass a variable as a function parameter, is a new copy of the variable value or a memory reference javascript

function changeObject(x) {
  x = { member: "bar" };
  console.log("in changeObject: " + x.member);
}

function changeMember(x) {
  x.member = "bar";
  console.log("in changeMember: " + x.member);
}

var x = { member: "foo" };

console.log("before changeObject: " + x.member);
changeObject(x);
console.log("after changeObject: " + x.member); /* change did not persist */

console.log("before changeMember: " + x.member);
changeMember(x);
console.log("after changeMember: " + x.member); /* change persists */
 Run code snippetHide results
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #I #pass #variable #function #copy #variable #memory #reference #javascript
ADD COMMENT
Topic
Name
2+5 =