> For the complete documentation index, see [llms.txt](https://choubey.gitbook.io/javascript-interview-questions/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://choubey.gitbook.io/javascript-interview-questions/question-47.md).

# Question 47

### Question

How would you create a shallow copy of an object using prototypes?

### Answer

Here's how you can create a shallow copy of an object in JavaScript, leveraging prototypes:

```javascript
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)


```

**Explanation:**

1. **`Object.create(Object.getPrototypeOf(obj))`:**
   * `Object.getPrototypeOf(obj)` retrieves the prototype of the original object.
   * `Object.create()` creates a new object with this retrieved prototype. This ensures that the newly copied object inherits from the same prototype chain as the original object, meaning its methods will likely be identical.
2. **Iterating and Copying Properties:**
   * The `for...in` loop iterates over each property in the original object.
   * `Object.prototype.hasOwnProperty.call(obj, key)` checks if a property belongs to the original object itself (and not inherited from its prototype). This is important because we only want to copy properties directly owned by the original object.
3. **`newObj[key] = obj[key]`:**
   * Each property of the original object is copied to the new object (`newObj`).

**Important Notes about Shallow Copies:**

* **Nested Objects:** A shallow copy will only create a reference to nested objects within the original object. Changes to nested objects in the copy *will* affect the original object, as they share the same references.
* **Arrays:** Shallow copies of arrays also maintain references to their elements. Modifications to elements within the copied array will affect the original array.
