-
Notifications
You must be signed in to change notification settings - Fork 4.3k
[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
Merged
Merged
Changes from 19 commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
d0dd9bd
[Edit] SQL: DATEDIFF()
mamtawardhani 9f5c19b
Update datediff.md
mamtawardhani c32e9f3
Merge branch 'Codecademy:main' into main
mamtawardhani 4170ba2
Merge branch 'Codecademy:main' into main
mamtawardhani 8325585
Merge branch 'Codecademy:main' into main
mamtawardhani 8f6f8e8
Merge branch 'Codecademy:main' into main
mamtawardhani e4c54e8
Merge branch 'Codecademy:main' into main
mamtawardhani 7b3b9c0
Merge branch 'Codecademy:main' into main
mamtawardhani 27ecefd
Merge branch 'Codecademy:main' into main
mamtawardhani 0392da4
Merge branch 'Codecademy:main' into main
mamtawardhani d550fa7
Merge branch 'Codecademy:main' into main
mamtawardhani 793be7d
Merge branch 'Codecademy:main' into main
mamtawardhani 2f03b61
Merge branch 'Codecademy:main' into main
mamtawardhani 25eb0ab
Merge branch 'Codecademy:main' into main
mamtawardhani 73e0e3b
Merge branch 'Codecademy:main' into main
mamtawardhani 44f4c63
Merge branch 'Codecademy:main' into main
mamtawardhani 545a8da
Merge branch 'Codecademy:main' into main
mamtawardhani a05c2f1
[Edit] JavaScript: .assign()
mamtawardhani 15c3c04
Update content/javascript/concepts/objects/terms/assign/assign.md
avdhoottt cc9f53d
Update content/javascript/concepts/objects/terms/assign/assign.md
avdhoottt 8df5157
Update content/javascript/concepts/objects/terms/assign/assign.md
avdhoottt dea9d04
Update content/javascript/concepts/objects/terms/assign/assign.md
avdhoottt 3fac67a
Update content/javascript/concepts/objects/terms/assign/assign.md
avdhoottt d502683
Update content/javascript/concepts/objects/terms/assign/assign.md
avdhoottt a82b976
Merge branch 'main' into js-objects-assign
avdhoottt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
197 changes: 167 additions & 30 deletions
197
content/javascript/concepts/objects/terms/assign/assign.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 using this 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: | ||
avdhoottt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ```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: | ||
avdhoottt marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ```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. | ||
avdhoottt marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.