JS Basics - Object Reference

Shows how objects are pass-by-reference

by Charlie Winfrey

JavaScript

var myObject = {
    id: 20,
    name: "Mr Object"
};

// This function will modify the original object
// It does not need to return anything
function modifyOriginal(x) {
    x.id = 5; // this uses the reference that was passed in
}

// This function will create a new object and set the property on it
// It does not affect the original object
function modifyNew(x) {
    x={}; // this creates a new pointer to the new object
    x.id=5;
}

console.log("original myObject", myObject);

modifyOriginal(myObject);
console.log("myObject", myObject);

modifyNew(myObject);
console.log("myObject", myObject);