Friday 14 December 2018

How to delete properties of an object in JavaScript?

You can use delete operator to delete the properties of an object in JavaScript.

HelloWorld.js
var employee = {
  firstName: "Hari Krishna",
  lastName: "Gurram",
  id: 123,

  toString: function() {
    return "[firstName = " + this.firstName + ", lastName = " + this.lastName + ", id = " + this.id + "]";
  }
}

console.log(employee.toString());

delete employee.firstName;
console.log(employee.toString());

delete employee.lastName;
console.log(employee.toString());

Output
[firstName = Hari Krishna, lastName = Gurram, id = 123]
[firstName = undefined, lastName = Gurram, id = 123]
[firstName = undefined, lastName = undefined, id = 123]

Previous                                                 Next                                                 Home

No comments:

Post a Comment