Object assign in JavaScript

Object assign in JavaScript

Object assign is a static method of JavaScript Object global.

Object assign is mainly used for merging two or more objects, where keys match Object assign overwrites one value of an object with the corresponding value of the same key in the second object.

Example usage of object assign;

const max = {
    name: 'max',
  type: 'dog',
    bread: 'fluffy'
}

Given a situation where you want to derive a new pet of a certain name you will not need to redefine the whole pet structure instead just add or replaced the characteristics of the pet to that of your desire;

const khloe = Object.assign(max, {
  name: 'khloe'
  type: 'cat',
  color: 'blue'
})

// output after running the code above on a JavaScript engine;

{
    "name": "khloe",
    "type": "kitty",
    "bread": "fluffy",
    "color": "blue"
}

You can notice that Object khloe is a clone of max except that khloe is a cat

Both pets however share characteristics of fluffiness the property fluffy remains unchanged for both pets

Reference and further reading;
Google chrome sample
S6 Object.assign() Sample,

Mozilla Object assign
Mozilla Object assign

Comments

Popular posts from this blog

How to get user's ip address in JavaScript

How to make a static http server in nodejs using express

Array concat method in JavaScript

What is 'this.' keyword in JavaScript

How to create promises in JavaScript