Object methods in JavaScript

We already have learnt about user defined object. In JavaScript, Object (with capital 'O') is javascript built-in object which provides some methods to work with user defined objects. Let us see them one by one.

Object.assign()

Object.assign() copies own enumerable properties of one object to anohter object.
What is own properties? By own properties means the properties should not be inherted from other object. Yes, object can inherit properties from other object. Remember, in this chapter, we said that every object are inherited from Object (built-in).
What is enumerable property? Enumerable properties are properties whose enumerable flag is true. When you assign any property to an object, enumerable flag is set to true by default. You can set it to false but we will see that after. When you run for...in loop, you can not get properties which has enumerable flag false.
Let us have a look at example.


var vehicle = {
    name: "BMW",
    type: "Car"
};

var vehicle1 = Object.assign({}, vehicle);
console.log(vehicle1);
//output: {
//    namme: "BMW",
//    type: "Car"
//  }

var targetObject = {owner: "John"};

var vehicle2 = Object.assign(targetObject, vehicle);
console.log(vehicle2);
//output: {
//    namme: "BMW",
//    type: "Car",
//    owner: "John"
//  }

console.log(targetObject);
//output: {
//    namme: "BMW",
//    type: "Car",
//    owner: "John"
//  }
                    

As from the above code, you can see that properties of vehicle are copied to vehicle1 which is a new cloned object.
Now, when you want to add properties of one object to another, add the targetObject as the first parameter and sourceObject (vehicle) as the second parameter.
In our case, properties of vehicle will be added to targetObject and the method will return targetObject. So vehicle2 === targetObject will be true.

Object.create()

Object.create(protoObject, [propertiesObject]) creates a new object using the existing object.
propertiesObject is optional. And if specified, then it should be property descriptor.


var emptyObject = Object.create({});
console.log(emptyObject);
//output: {}

var targetObject = {owner: "John"};

var vehicle2 = Object.assign(targetObject, { type: {value: "Car"}});
console.log(vehicle2);
//output: {
//    type: "Car",
//    owner: "John"
//  }

console.log(targetObject);
//output: {
//    owner: "John"
//  }
                    

As per the above code, when you pass an empty object, it creates an empty object.
When you pass an object with property descriptor, it will create add the property to the targetObject and will create a new object.

Property Descriptors

Simple meaning of Property Descriptor is that it describes property.
There are six descriptors of a property:

  • value

    It can be any JavaScript value string, object, number, function, boolean etc.

  • writable

    If true, you can change the property. If false, you can not change the property.

  • configurable

    If true, then you can change descriptors. If false, then you can not change descriptors.

  • enumerable

    If true, then property shows up during enumeration (Like in for...in loop). If false, it doesn't show up during enumeration.

  • get

    A function which serves as a getter.

  • set

    A function which serves as a setter. A function has only one argument which is the new value of the property.

Object.defineProperty()

Object.defineProperty(object, propertyName ,propertyDescriptor) defines a property on object or modifies an existing property. It returns the object.
A first argument is an object, the second argument is the name of the property and the third argument is propertyDescriptor.
Default value of

  • value is undefined
  • writable is false
  • configurable is false
  • enumerable is false
  • get is undefined
  • set is undefined


var vehicle = {};

Object.defineProperty(vehicle, "yearsOld",{
    value: 5,
    writable: false
});

console.log(vehicle);
//output: {
//  yearsOld: 5
//}

vehicle.yearsOld = 6;
// Error in strict mode
// If it doesn't throw error, then vehicle.yearsOld will be 5.

Object.defineProperty(vehicle, "yearsOld",{
    writable: true
});
// Error 
// You can not change the desrciptor now because configurable is set to false (default)
                    

When you add a property with descriptor writable = false, you will not be able to edit it. Just like the above code. When you will try to assign a new value, an error will be thrown.
Now, make "yearsOld" writable=true, So now, you can change "yearsOld" property.
Remember, it will affect only "yearsOld".
In above code, we only have provided value and configurable. So other descriptors are set to default.


var vehicle = {};

Object.defineProperty(vehicle, "yearsOld",{
    configurable: true,
    get(){ console.log("Gettter"); return this.years},
    set(newVal){ console.log("setter");this.years = newVal + "Some string" }
});

cosole.log(vehicle.yearsOld);
//output: Gettter
//        undefined

vehicle.yearsOld = 6;
//output: Setter

cosole.log(vehicle.yearsOld);
//output: Gettter
//        "6Some string"
                    

As per above code, we have defined getter and setter of property yearsOld.
getter returns the value from property years and setter sets the value to property years.
You can run some process on value which you are getting from/setting to the property, that is the main funda of getter and setter.

Object.defineProperties()

Object.defineProperties(obj, props) defines new properties or modifies properties.
With Object.defineProperty(), you can define one property and with Object.defineProperties() you can define many properties.


var vehicle = {};

Object.defineProperties(vehicle, {
    owner: {
        configurable: true,
        value: "John Doe"
    },
    color: {
        value: "Red"
    }
});
                    

You can see from above code that, you can add multiple properties using Object.defineProperties()

Object.getOwnPropertyDescriptor()

Now, you already have set the property descriptors. You can get the property descriptors using Object.getOwnPropertyDescriptor(obj, prop).
The first argument is the object and the second argument is the property.


var vehicle = {
    owner: "John Doe"
};

Object.defineProperty(vehicle, "yearsOld",{
    value: 5,
    writable: false
});

var propDescriptor = Object.getOwnPropertyDescriptor(vehicle, "yearsOld");
console.log(propDescriptor);
//output: {
//    configurable: false
//    enumerable: false
//    value: 5
//    writable: false
//} 

var propDescriptor1 = Object.getOwnPropertyDescriptor(vehicle, "owner");
console.log(propDescriptor1);
//output: {
//    configurable: true
//    enumerable: true
//    value: "John Doe"
//    writable: true
//} 
                    

Compare propDescriptor and propDescriptor1.
The property added by Object.defineProperty() has has all the property descriptor to false, because they are set to default. While the property directly added to the object is set to true because that is the default property descriptors of directly set property.

Object.getOwnPropertyDescriptors()

When you want to get property descriptors of every property of object, Object.getOwnPropertyDescriptors(obj) is used.
The only argument is the object.


var vehicle = {
    owner: "John Doe"
};

Object.defineProperty(vehicle, "yearsOld",{
    value: 5,
    writable: false
});

var propDescriptors = Object.getOwnPropertyDescriptors(vehicle);
console.log(propDescriptor);
//output: {
//    yearsOld: {
//      configurable: false,
//      enumerable: false,
//      value: 5,
//      writable: false 
//    },
//    owner: {
//      configurable: true,
//      enumerable: true,
//      value: "John Doe",
//      writable: true 
//    }
//}
                    

Object.keys()

Object.keys(obj) method returns the array of property names of obj.


var vehicle = {
    owner: "John Doe",
    color: "Red"
};

var keys = Object.keys(vehicle);
console.log(keys);
//output: ["owner", "color"]
                    

Object.values()

Object.values(obj) returns the array of own enumerable property values of obj.


var vehicle = {
    owner: "John Doe",
    color: "Red"
};

var values = Object.values(vehicle);
console.log(values);
//output: ["John Doe", "Red"]
                    

Object.seal()

Object.seal(obj) prevents new properties to be added or deleted and make all the existing properties non configurable (Descriptors). Values of the existing properties can still be changed.


var vehicle = {
    owner: "John Doe",
    color: "Red"
};

Object.seal(vehicle);

vehicle.owner = "New Owner";
console.log(vehicle.owner);
//output: "New Owner"

vehicle.type = "car";
//Error in Strict mode

console.log(vehicle);
//output: {
//    owner: "John Doe",
//    color: "Red"
//}
                    

Object.freeze()

Object.freeze(obj) makes obj non-changable. You can not add new property, delete existing property, makes all the property non-configurable and non-writable.
In Object.seal(), you can change the value of the properties. Also, you can not change the property descriptors ( non-configurable ). So property which is writable will remain writable after the seal.
In Object.freeze(), you can not change the value of the properties. And also property descriptors writable and configurable are changed to false.


var vehicle = {
    owner: "John Doe"
};

var propDescriptor1 = Object.getOwnPropertyDescriptor(vehicle, "owner")

console.log(propDescriptor1);
//output: {
//    configurable: true
//    enumerable: true
//    value: "John Doe"
//    writable: true
//} 

Object.freeze(vehicle);

propDescriptor1 = Object.getOwnPropertyDescriptor(vehicle, "owner")

console.log(propDescriptor1);
//output: {
//    configurable: false
//    enumerable: true
//    value: "John Doe"
//    writable: false
//} 

vehicle.owner = "New Owner";
//Error in Strict mode

console.log(vehicle.owner);
//output: "John Doe"
                    

Object.isSealed()

Object.isSealed(obj) checks if obj is sealed or not.


var vehicle = {
    owner: "John Doe",
    color: "Red"
};

Object.isSealed(vehicle);
//output: false

Object.seal(vehicle);

Object.isSealed(vehicle);
//output: true
                    

Object.isFrozen()

Object.isFrozen(obj) checks if obj is frozen or not.


var vehicle = {
    owner: "John Doe",
    color: "Red"
};

Object.isFrozen(vehicle);
//output: false

Object.freeze(vehicle);

Object.isFrozen(vehicle);
//output: true
                    

Conclusion

There are many methods in Object but we have learned few useful of them.
So you have learned Basic JavaScript Tutorials. We will add Advanced JavaScript Tutorials in new future.
Till then, keep learning !!!