Skip to content

[Edit] JavaScript: .assign() #7031

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
197 changes: 167 additions & 30 deletions content/javascript/concepts/objects/terms/assign/assign.md
Original file line number Diff line number Diff line change
@@ -1,62 +1,199 @@
---
Title: '.assign()'
Description: 'Returns an object that contains the contents of the objects passed.'
Description: 'Copies all enumerable own properties from one or more source objects to a target object.'
Subjects:
- 'Web Development'
- 'Computer Science'
- 'Web Development'
Tags:
- 'Properties'
- 'Objects'
- 'Functions'
- 'Methods'
- 'Objects'
- 'Properties'
CatalogContent:
- 'introduction-to-javascript'
- 'paths/create-a-back-end-app-with-javascript'
- 'paths/front-end-engineer-career-path'
---

The **`Object.assign()`** method is used to modify a "destination" object with the contents of one or more objects passed to the method. If there are duplicate keys between the objects the values in the destination object will be overridden in the assignment.
The **`Object.assign()`** method copies all enumerable own properties from one or more source [objects](https://www.codecademy.com/resources/docs/javascript/objects) to a target object. It performs a shallow copy, meaning that nested objects are not cloned, but their references are copied to the target object. This method modifies and returns the target object, making it a powerful tool for object manipulation and merging.

`.assign()` is commonly used for object cloning, merging configuration objects, copying properties between objects, and implementing object composition patterns. It serves as a fundamental utility in modern JavaScript development, particularly in scenarios involving state management, data transformation, and functional programming approaches where immutable-like operations on objects are required.

## Syntax

```pseudo
Object.assign(destinationObj, sourceObj)
// Or
Object.assign(destinationObj, sourceObj, ... nObj)
Object.assign(target, source1, source2, ..., sourceN)
```

- `destinationObj`: The object to be modified. The entries of the other objects passed will be added to this object.
- `sourceObj`: The object(s) that will be used to supplement the "destination" object.
**Parameters:**

- `target`: Required. The target object that will receive properties from the source objects. This object is modified and returned by the method.
- `source1, source2, ..., sourceN` (Optional): One or more source objects containing the properties to be copied to the target object.

## Example
**Return value:**

The following code demonstrates a basic implementation of the `Object.assign()` method:
The `.assign()` method returns the modified target object with all enumerable own properties from the source objects copied to it.

## Example 1: Basic Object Copying

This example demonstrates the fundamental usage of `.assign()` for copying properties from one object to another:

```js
const eastLibrary = {
1: 'Green Eggs and Ham',
2: 'Cat in the Hat',
3: 'Hop on Pop',
// Create source and target objects
const targetObj = {
name: 'Alice',
age: 25,
};

const westLibrary = {
3: 'Lorax',
4: 'How the Grinch Stole Christmas',
5: 'The Zax',
const sourceObj = {
age: 30,
city: 'New York',
occupation: 'Developer',
};

const seussBooks = Object.assign(eastLibrary, westLibrary);
console.log(seussBooks);
// Copy properties from source to target
const result = Object.assign(targetObj, sourceObj);

console.log(result);
console.log(targetObj === result);
```

The output of this code will be:

```shell
{ name: 'Alice', age: 30, city: 'New York', occupation: 'Developer' }
true
```

In this example, `.assign()` copies all enumerable properties from `sourceObj` to `targetObj`. When properties exist in both objects (like `age`), the source object's values overwrite the target object's values. The method returns a reference to the modified target object.

## Example 2: Object Cloning and Merging

This example shows how to use `.assign()` for creating object clones and merging multiple objects together:

```js
// Original object to clone
const originalUser = {
id: 1,
username: 'john_doe',
preferences: {
theme: 'dark',
notifications: true,
},
};

// Create a shallow clone using empty object as target
const clonedUser = Object.assign({}, originalUser);

// Modify the clone
clonedUser.username = 'jane_doe';
clonedUser.preferences.theme = 'light'; // This affects original too (shallow copy)

console.log('Original:', originalUser.preferences.theme);

console.log('Clone:', clonedUser.preferences.theme);

// Merging multiple configuration objects
const defaultConfig = { timeout: 5000, retries: 3 };
const userConfig = { timeout: 8000, debug: true };
const envConfig = { apiUrl: 'https://api.example.com' };

const finalConfig = Object.assign({}, defaultConfig, userConfig, envConfig);

console.log(finalConfig);
```

This will return the following output:
The output produced by this code is:

```shell
Original: light
Clone: light
{
'1': 'Green Eggs and Ham',
'2': 'Cat in the Hat',
'3': 'Lorax',
'4': 'How the Grinch Stole Christmas',
'5': 'The Zax'
timeout: 8000,
retries: 3,
debug: true,
apiUrl: 'https://api.example.com'
}
```

> **Note:** The reassignment in the code above is optional. The following is true: `eastLibrary === suessBooks`.
This example illustrates both object cloning and merging scenarios. The shallow copy behavior is important to understand: nested objects are shared between the original and clone, while primitive values are independent copies.

## Example 3: State Management and Updates

This example demonstrates how `.assign()` can be used in state management scenarios, particularly for creating updated versions of state objects:

```js
// Initial application state
const initialState = {
user: {
id: null,
name: '',
isLoggedIn: false,
},
ui: {
loading: false,
error: null,
},
data: [],
};

// Function to update user login state
function loginUser(state, userData) {
return Object.assign({}, state, {
user: Object.assign({}, state.user, {
id: userData.id,
name: userData.name,
isLoggedIn: true,
}),
});
}

// Function to set loading state
function setLoading(state, isLoading) {
return Object.assign({}, state, {
ui: Object.assign({}, state.ui, {
loading: isLoading,
}),
});
}

// Simulate user login
const loginData = { id: 123, name: 'Sarah Connor' };
const stateAfterLogin = loginUser(initialState, loginData);

console.log('Initial state user:', initialState.user.isLoggedIn);

console.log('Updated state user:', stateAfterLogin.user.isLoggedIn);

// Chain state updates
const loadingState = setLoading(stateAfterLogin, true);

console.log('Loading state:', loadingState.ui.loading);

// Original state remains unchanged
console.log('Original loading:', initialState.ui.loading);
```

The output produced by this code will be:

```shell
Initial state user: false
Updated state user: true
Loading state: true
Original loading: false
```

This example shows practical usage in state management where `Object.assign()` creates new state objects without mutating the original state, following immutable update patterns commonly used in frameworks like Redux.

## Frequently Asked Questions

### 1. What is the difference between `Object.create()` and `Object.assign()` in JavaScript?

`Object.create()` creates a new object with a specified prototype, while `Object.assign()` copies properties from source objects to a target object. `Object.create()` establishes prototype inheritance, whereas `Object.assign()` performs property copying without affecting the prototype chain.

### 2. Does `Object.assign()` perform deep or shallow copying?

`Object.assign()` performs shallow copying. It copies property values directly, so nested objects are copied by reference rather than being deeply cloned. For deep copying, you need alternative approaches like `structuredClone()` or custom recursive functions.

### 3. Can `Object.assign()` copy non-enumerable properties?

No, `Object.assign()` only copies enumerable own properties. Non-enumerable properties, inherited properties, and properties from the prototype chain are not copied. Use `Object.getOwnPropertyDescriptors()` with `Object.defineProperties()` for copying all property types.