Object methods in JavaScript Object methods in JavaScript

Page content

This post describes the usage of various Object methods like Object.create(), Object.assign(), Object.freeze(), Object.seal() and many more available in JavaScript with examples.

Object.create()

The Object.create() method is used to create a new object with its prototype set to existing object.

var car = {
    color: "black",
    brand: "Toyota",
    drive: function(){
      console.log(`Driving a ${this.isTopModel ? 'top model' : ''} ${this.color} color ${this.brand} car`);
    }
}
var newCar = Object.create(car);
newCar.brand = "Honda";
newCar.isTopModel = true;

console.log(car.isPrototypeOf(newCar)); //true
newCar.drive();
Output
true Driving a top model black color Honda car

Here newCar creates a completely new object with its prototype set to Car. We set the brand and isTopModel values whereas value of color will be inherited. When we call drive() method, it finds the drive() in the prototype chain on car and execute.

Object.assign()

Object.assign() is used to copy the properties and functions of one object in another object.

We can merge two objects using Object.assign() as follows:-

// Initialize an object
const favorites = {
    color: 'Red',
    number: 5   
};

// Initialize another object
const somemore = {
    fruit: 'Mango',
    movies: ["Spider Man", "Conjuring"],   
};

// Merge the objects
console.log(Object.assign(favorites, somemore));
Output
{color: "Red", number: 5, fruit: "Mango", movies: ["Spider Man", "Conjuring"]}

Also can be used in Class constructor to assign all values to this as follows:

class Car {
    constructor(brand, color, price){
        Object.assign(this, {brand, color, price});
    }
}

Object.freeze()

Object.freeze() freezes the state of an Object once this method is called. It ignores if any existing property is modified, and if any new property is added.

// Initialize an object
const user = {
    username: 'admin',
    password: 'password@123'
};
// Freeze the object
Object.freeze(user);

user.password = '*******';
user.active = true;

console.log(user);
Output
{username: "admin", password: "password@123"}

Object.seal()

Object.seal() seals the state of an Object once this method is called. It allows the modification of existing properties, but ignores if any new property is added.

// Initialize an object
const user = {
    name: 'admin',
    password: 'password@123'
};
// Seal the object
Object.seal(user);

user.password = '*******';
user.active = true;

console.log(user);
Output
{name: "admin", password: "*******"}

Object.defineProperty()

Object.defineProperty() is used to define new property in existing object.

Property can be defined with following options:

  • value: defaults to undefined, if value of the property is not provided
  • writable: deafults to false, if true means value of the property can be changed
  • configurable: defaults to false, if true means property can be deleted
  • enumerable: defaults to false, if true means property can be enumerated such as in a for..in loop
var user = {};

Object.defineProperty(user, "name", {
  value: "admin"
});

console.log(user);

is equivalent to

var user = {};

Object.defineProperty(user, "name", {
  value: "admin",
  writable: false,
  configurable: false,
  enumerable: false
});

console.log(user);
Output
{name: "admin"}

Object.defineProperties()

Object.defineProperties() can be used to define multiple properites in existing object.

var user = {};

Object.defineProperties(user, {
  name: {
    value: "admin",
    writable: true,
    enumerable: true
  },
  password: {
    value: 'password@123',
    writable: false,
    enumerable: false
  }      
});

console.log(user);
Output
{name: "admin", password: "password@123"}

Object.keys(), Object.values() & Object.entries()

Object.keys(), Object.values() and Object.entries() can be used iterator from the object as follows:

let favorites = {
    color: 'Red',
    number: 5,
    vegan: true,
    movies: ["Spider Man", "Conjuring"]   
};

console.log("keys", Object.keys(favorites));
console.log("values", Object.values(favorites));
console.log("entries", Object.entries(favorites));
Output
keys ["color", "number", "vegan", "movies"] values ["Red", 5, true, ["Spider Man", "Conjuring"]] entries [ ["color", "Red"], ["number", 5], ["vegan", true], ["movies", ["Spider Man", "Conjuring"] ]

Object.keys() and Object.entries() can be used to iterate through the keys and values of an object as follows:-

Object.keys(favorites).forEach(key => console.log(`${key}: ${favorites[key]}`));

Object.entries(favorites).forEach(entry => console.log(`${entry[0]}: ${entry[1]}`));

Object.is()

ES6 has introduced a new method Object.is() to compare two values, it works very much similar to strict comparison operator === and also avoid confusion of NaN comparisons and +0/-0 comparisons. It is recommended to use Object.is() for value comparisons.

let’s check it out,

console.log(Object.is("cnc", "cnc"));     // true, same content and type
console.log(Object.is(12345, 12345));     // true, same content and type
console.log(Object.is(false, false));     // true, same content and type

console.log(Object.is(12345, "12345"));   // false, different type
console.log(Object.is(0, false));         // false, different type
console.log(Object.is("", false));        // false, different type
console.log(Object.is(null, undefined));  // false, different type

console.log(Object.is([], []));           // false, both refers to different object in memory
console.log(Object.is([1, 2], [1, 2]));   // false, both refers to different object in memory
console.log(Object.is({}, {}));           // false, both refers to different object in memory

var array1 = [1, 2, 3, 4, 5];
var array2 = array1;
console.log(Object.is(array1, array2));   // true, both refers to same array

var obj1 = { app : "cnc"};
var obj2 = obj1;
console.log(Object.is(obj1, obj2));       // true, both refers to same object

console.log(NaN === NaN);                 // false, confusing, content and type is same
console.log(Object.is(NaN, NaN));         // true, es6 is good, same content and type

console.log(+0 === -0);                   // true, confusing, content is different
console.log(Object.is(+0, -0));           // false, es6 is good, different content

Summary

Javascript Object provides very useful methods to

  • create a new object using Object.create()
  • copy object using Object.assign()
  • protect object using Object.freeze() and Object.seal()
  • define object properties using Object.defineProperty() and Object.defineProperties()
  • iterate through object using Object.keys(), Object.values() and Object.entries()
  • compare objects using Object.is()