Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Assign

Sometimes you want to compare two object of identical structure but the properties may have different values. In the scenario, you may have created a copy of Object1 to create Object2. This presents a problem because these are reference types.... so any changes you make in Object2 will also be made in Object1 since Object2 and Object1 share the same memory pointer.

Consider the following example:


// example 1
let Spaceship1 = { Type: "X-Wing", Alliance: "Resistance" };
let Spaceship2 = Spaceship1;        // make a copy
Spaceship2.Type = "Y-Wing";         // change the copy
// what?  that doesn't look right, we changed both!
$("#demo1").html(`The Type of Spaceship1 is ${Spaceship1.Type} and the type of Spaceship2 is ${Spaceship2.Type}.`);

The solution is to use the object method assign introduced in ECMA 6. The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign


// example 2
let Spaceship1a = { Type: "X-Wing", Alliance: "Resistance" };
let Spaceship2a = Object.assign({}, Spaceship1a);
Spaceship2a.Type = "Y-Wing";         // change the copy
$("#demo2").html(`The Type of Spaceship1a is ${Spaceship1a.Type} and the type of Spaceship2a is ${Spaceship2a.Type}.`);