ES6 object methods

ES6 introduces a few static helper methods for objects. Object.assign is a helper method that replaces popular mixins to perform a shallow copy of an object.

Copy properties using Object.assign

This method is used to copy properties of the target object into the source object. In other words, this method merges the source object with the target object and modifies the target object:

    let a = {} 
    Object.assign(a, { age: 25 }) 
    console.log(a)  //{"age":25} 

The first parameter to Object.assign is the target on which source properties are copied. The same target object is returned to the caller. Existing properties are overwritten, while properties that aren't part of the source object are ignored:

    let a = {age : 23, gender: "male"} 
    Object.assign(a, { age: 25 })    // age overwritten, but gender ignored 
    console.log(a)  //{"age":25, "gender":"male"} 

Object.assign can take multiple source objects. You can write Object.assign(target, source1, source2). Here is an example:

    console.log(Object.assign({a:1, b:2}, {a: 2}, {c: 4}, {b: 3})) 
    //Object { 
    //"a": 2,  
    //"b": 3, 
    //"c": 4 
    // 

In this snippet, we are assigning properties from multiple source objects. Also, notice how Object.assign() returns the target object, which we in turn use inside console.log().

One point to note is that only enumerable own (non-inherited) properties can be copied using Object.assign(). Properties from the prototype chain (will be discussed later in this chapter when we talk about Inheritance) are not considered. Our earlier discussion of enumerable properties will help you understand this distinction.

In the following example, we will create a non-enumerable property using defineProperty() and validate the fact that Object.assign() ignores that property:

    let a = {age : 23, gender: "male"} 
    Object.defineProperty(a, 'superpowers', {enumberable:false, value: 'ES6'}) 
    console.log(

The property defined as superpowers has the enumerable attribute set to false. While copying properties, this property is ignored.

Compare values with Object.is

ES6 provides a slightly precise way of comparing values. We have discussed the strict equality operator ===. However, for NaN and -0 and +0, the strict equality operator behaves inconsistently. Here is an example:

    console.log(NaN===NaN) //false 
    console.log(-0===+0) //true 
    //ES6 Object.is 
    console.log(Object.is(NaN,NaN)) //true 
    console.log(Object.is(-0,+0)) //false 

Apart from these two cases, Object.is() can safely be replaced with the === operator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.214.60