Rangle.io: React Training
gitbook
gitbook
  • Introduction
  • Setup
  • Functional JavaScript
  • ES6 constructs
    • Default Params
    • Template Literals
    • Destructuring
    • Arrow Functions
    • Promises
    • let and const
    • Modules
  • Thinking in Components
    • Atomic Design
    • Atomic Component Principles
    • Benefits of This Approach
    • The Process
    • Task #1
  • React Components
    • Stateless Components
    • Stateful Components
    • Stateful vs Stateless Components
    • Composition
    • Task #2
    • Task #3
    • Task #4
    • Task #5
  • Immutable
    • What Is Immutability?
    • The Case for Immutability
    • JavaScript Solutions
      • Object.assign
      • Object.freeze
    • Immutable.js Basics
      • Immutable.Map
        • Map.merge
      • Nested Objects
        • Deleting Keys
        • Maps are Iterable
      • Immutable.List
      • Performance
      • Persistent and Transient Data Structures
      • Official Documentation
    • Exercises
      • Task #1
      • Task #2
      • Task #3
      • Task #4
      • Task #5
      • Task #6
      • Task #7
  • Redux
    • Review of Reducers and Pure Functions
    • Redux Reducers
    • Redux Actions
    • Configuring your Application to use Redux
    • Using Redux with Components
    • Redux and Component Architecture
  • Routing
    • React Router
    • Router Redux
  • Forms
    • Redux Form
  • Testing
    • Setup
    • Components
    • Reducers
    • Actions
Powered by GitBook
On this page

Was this helpful?

  1. Immutable
  2. JavaScript Solutions

Object.assign

Object.assign lets us merge one object's properties into another one, replacing values of properties with matching names. We can use this to copy an object's values without altering the existing one.

let movie1 = {
  name: 'Star Wars',
  episode: 7
};

let movie2 = Object.assign({}, movie1);

movie2.episode = 8;

console.log(movie1.episode); // writes 7
console.log(movie2.episode); // writes 8

As you can see, although we have some way of copying an object, we haven't made it immutable, since we were able to set the episode's property to 8. Also, how do we modify the episode property in this case? We do that through the assign call:

let movie1 = {
  name: 'Star Wars',
  episode: 7
};

let movie2 = Object.assign({}, movie1, { episode: 8 });

console.log(movie1.episode); // writes 7
console.log(movie2.episode); // writes 8
PreviousJavaScript SolutionsNextObject.freeze

Last updated 6 years ago

Was this helpful?