Salesforce Certified JavaScript Developer free question 3 / 10 · Domain 2: Objects, Functions, and Classes
A developer copies a settings object and then changes the copy. const original = { name: 'report', tags: ['draft'] }; const copy = Object.assign({}, original); copy.tags.push('final'); console.log(original.tags.length); What is logged?
- 1, because the push changes the copy and the original keeps its own tags array
- 0, because Object.assign copies the properties whose values are strings
- 2, because the copy holds a reference to the same tags array as the original
- 1, because Object.assign makes a deep copy of the arrays and objects it finds in the source
Show the answer and explanation
Answer: C
Why this is correct
Object.assign copies own enumerable properties from the source to the target. If a source value is a reference to an object, it only copies the reference value. copy.tags and original.tags are the same array, so pushing final through the copy makes original.tags.length equal 2.
Why the other options are wrong
"1, because Object.assign makes a deep copy of the arrays and objects it finds in the source" … Object.assign copies property values. When a value is an object, only the reference is copied. The page recommends structuredClone() for deep cloning.
"1, because the push changes the copy and the original keeps its own tags array" … The two objects point to one array, so a push through either object is visible through both.
"0, because Object.assign copies the properties whose values are strings" … Object.assign copies all own enumerable properties, whatever their value type, so the tags property is copied as a reference.
Key points
Object.assign and spread make shallow copies. Nested objects and arrays stay shared. For deep cloning use structuredClone().