JavaScript Basics: Object.assign

The function Object.assign is used to assign the values of “enumerable” and “own” properties from one or more source objects to a target object (first argument). If the properties have getters or setters, they will be invoked. This is what the word “assign” means, so it's not just copying values from an object to another.

Here is an example:

    class Test {
        constructor(arg) {
            Object.assign(this, arg);
        }
    }

In fact, this is my favorite use case for this operation. The above code gives you the power to assign any properties of the newly created object in the constructor.

Remember that the function can accept multiple source objects as further arguments. This function overwrites any values that already exist in the target object.


Related Posts

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center