In JavaScript, objects are reference types, while primitive types (like numbers, strings, and booleans) are value types. This means that when we pass an object to a function or assign it to a new variable, the object is not copied, but a reference to the object is passed or assigned.
Here is an example that demonstrates the difference between object reference and value in JavaScript:
// Define an object
var person = {
name: 'John Doe',
age: 30
};
// Define a function that accepts an object as a parameter
function updatePerson(obj) {
// Update the object's properties
obj.name = 'Jane Doe';
obj.age = 35;
}
// Call the function and pass in the object
updatePerson(person);
// Log the updated object's properties to the console
console.log(person.name); // 'Jane Doe'
console.log(person.age); // 35
In this example, we are defining an object named person
that includes data properties for the name and age of a person. We are then defining a function named updatePerson()
that accepts an object as a parameter. The function updates the object’s properties with new values.
We are then calling the updatePerson()
function and passing in the person
object as an argument. When the function is executed, the person
object’s properties are updated with the new values.
Finally, we are logging the updated object’s properties to the console. This shows how the object reference is passed to the function and the changes to the object’s properties are applied to the original object.
This demonstrates the difference between object reference and value in JavaScript. When an object is passed to a function or assigned to a new variable, a reference to the object is passed or assigned, not a copy of the object.
I hope you find this useful. Please comment if you have any questions.