How TO – Remove a Property from an Object in JavaScript

JavaScript is the world’s most popular programming language. JavaScript is the programming language of the Web. JavaScript is easy to learn. In this simple tutorial we will learn to remove a property of a JavaScript object.

A sample JavaScript object is like:

var student = {
  firstName:"David",
  lastName:"Manual",
  age:20,
  hairColor:"black"
};

In our example we will use the object above. First, let us see our tool, the delete operator.

The delete operator

In JavaScript the delete operator is used to delete or remove object properties. The delete operator in JavaScript is designed to be used on object properties only. It has no effect on other JavaScript variables or functions.

Syntax

delete object.property
delete object[property]

Remove a Property – Example

Let’s remove the property named hairColor. The following code will remove the hairColor from the student object:

delete student.hairColor

Alternately you can also use “array notation” to delete an object property by its name.

delete student["hairColor"]

If you do console.log(student.hairColor) before and after the above command, it would print black and undefined.

console.log(student.hairColor) //before: prints "color"
console.log(student.hairColor) //after: prints "undefined"

Conclusion

Using delete operator in JavaScript an Object property can be deleted or removed from a JavaScript object.

Leave a Reply