function changeFoodProperty(obj)
{
// Change the property. This affects
// the originally passed object.
obj.food = "noodles";
}
// The 'food' property starts off as "pizza"
let myObject = {
food: "pizza"
};
console.log(`First, the food is: ${myObject.food}`);
// Calling the function changes the 'food' property
changeFoodProperty(myObject);
// Log the 'food' property again - it's now "noodles"
console.log(`Second, the food is: ${myObject.food}`);
Remember that in general:
- Strings and numbers are passed by value - assigning them or passing them to functions will make a copy
- Objects are passed by reference - assigning them or passing them to functions will reference the same object
These are key rules to know when writing JavaScript code. It might seem inconsistent at first, but it's actually a useful feature that you can depend on. It's also often more efficient to pass objects by reference: if you need to pass a large and complex object to a function, copying it could be a relatively time-consuming operation that considerably slows down the program. Passing it by reference avoids the need to copy anything, ensuring the program runs efficiently. Copying strings and numbers is generally a quick and simple thing for programs to do, so the efficiency difference isn't so important there.
Equality
You can also use the equality operators ===
and !==
to test if references refer to the same object. Note this only checks the reference - it doesn't check any of the object properties or their values, only if the two things refer to exactly the same object. The example below demonstrates how this works.
// Create an object
let objA = {
food: "pizza"
};
// objB refers to the same object as objA
let objB = objA;
// objC refers to a different object, even though
// it has the same property and value
let objC = {
food: "pizza"
};
// Display equality
console.log("objA === objB: ", objA === objB); // true
console.log("objA === objC: ", objA === objC); // false