What will be logged when executing the following code? let person = { name: 'Lydia' }; const members = [person]; person = null; console.log(members);

Prepare for the Salesforce JavaScript Developer Exam. Utilize comprehensive quizzes, flashcards, and multiple choice questions with hints and explanations. Boost your exam readiness!

Multiple Choice

What will be logged when executing the following code? let person = { name: 'Lydia' }; const members = [person]; person = null; console.log(members);

Explanation:
In this scenario, the code creates an object called `person` with a property `name` set to 'Lydia'. It then initializes an array called `members` that contains the `person` object as an element. The important point here is that at this stage, the `members` array holds a reference to the `person` object. When the code sets `person` to `null`, it does not affect the reference stored in the `members` array. The `members` array still holds a reference to the original `person` object, which has its property `name` equal to 'Lydia'. Therefore, when you log `members`, it will show that it contains the object with the name property. Given this understanding, the output logged to the console will be `[{ name: "Lydia" }]`, as it reflects the original object held in the array before the reference to `person` was set to `null`. This illustrates how JavaScript handles object references and the mutability of objects, differentiating between object references and primitive values.

In this scenario, the code creates an object called person with a property name set to 'Lydia'. It then initializes an array called members that contains the person object as an element. The important point here is that at this stage, the members array holds a reference to the person object.

When the code sets person to null, it does not affect the reference stored in the members array. The members array still holds a reference to the original person object, which has its property name equal to 'Lydia'. Therefore, when you log members, it will show that it contains the object with the name property.

Given this understanding, the output logged to the console will be [{ name: "Lydia" }], as it reflects the original object held in the array before the reference to person was set to null. This illustrates how JavaScript handles object references and the mutability of objects, differentiating between object references and primitive values.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy