Code highlights logo

Learn

Objects

Pass By Reference

Pass by reference means that when you pass an object to a function, any modifications made to the object inside the function will affect the original object outside the function.

For example, consider the following code:

1let person = {
2 name: "John",
3 age: 25
4};
5
6function celebrateBirthday(person) {
7 person.age++;
8}
9
10celebrateBirthday(person);
11console.log(person.age); // Output: 26

In this code, we have an object person with a name and age property. We then define a celebrateBirthday function that takes a person parameter and increments their age by 1.

When we call celebrateBirthday(person), the person object is passed to the function by reference. Any changes made to the person object inside the function will affect the original person object outside the function.

After calling celebrateBirthday(person), we can see that the age property of the person object is incremented by 1, resulting in an output of 26.


Instructions

1.

Declare a new variable called updatedPerson and assign it the value of the person object.

2.

Call the updatePerson function passing the updatedPerson object as an argument.

3.

Print the updatedPerson object to the console.

Sign up to start coding

Already have an account?

Sign In

Course content