Question 47
Question
Answer
function shallowCopy(obj) {
const newObj = Object.create(Object.getPrototypeOf(obj)); // Create a new object with the same prototype
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
newObj[key] = obj[key];
}
}
return newObj;
}
// Example usage:
const originalObj = { name: "Alice", age: 30, hobbies: ["reading", "coding"] };
const copiedObj = shallowCopy(originalObj);
console.log(copiedObj); // Output: { name: "Alice", age: 30, hobbies: [ 'reading', 'coding' ] }
console.log(copiedObj === originalObj); // false (different objects)
Last updated