JS-Dev-101 practice question 18 of 25

Refer to the code below: 01 const objBook = { 02 title: 'JavaScript', 03 }; 04 Object.preventExtensions(objBook); 05 const newObjBook = objBook; 06 newObjBook.author = 'Robert'; What are the values of objBook and newObjBook respectively?

Full set: 148 questions
Answer options
A: { title: "JavaScript" } { title: "JavaScript" } Correct answer
B: { author: "Robert", title: "JavaScript" } undefined
C: { author: "Robert" } { author: "Robert", title: "JavaScript" }
D: { author: "Robert", title: "JavaScript" } { author: "Robert", title: "JavaScript" }
Correct Answer:
A. { title: "JavaScript" } { title: "JavaScript" }
Explanation

The Object.preventExtensions() method is called on objBook (line 04), making it non-extensible. This means no new properties can be added to it. In line 05, newObjBook is assigned a reference to the same object as objBook, not a copy. Therefore, newObjBook also refers to the non-extensible object. The attempt to add the author property on line 06 fails silently in non-strict mode. Both variables continue to point to the original, unchanged object.

Why Incorrect

B. The object is not modified due to preventExtensions, and newObjBook is a reference to the object, not undefined.
C. The author property is never added, and both variables point to the same object, so their values must be identical.
D. The author property is not added because the object was made non-extensible before the assignment attempt.

References

1. MDN Web Docs, Object.preventExtensions(). "The Object.preventExtensions() static method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object)."

2. ECMAScript® 2024 Language Specification, Section 10.1.11 [[PreventExtensions]] (). "Once the [[Extensible]] internal slot of an object has been set to false, it may not be changed back to true."

3. MDN Web Docs, "Grammar and types - Data structures". "Objects in JavaScript... are reference types. Two distinct objects are never equal, even if they have the same properties... two variables that refer to the same object are equal."

Scroll to Top