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

Adding Gameover and introduction screen on HTML Canvas

FlappingBird JS13K Games

How to set content disposition header for nginx server to force content download

Snake monochrome (JS1024)

How to make a Snake Game using JavaScript and html5