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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var student = {
firstName:"David",
lastName:"Manual",
age:20,
hairColor:"black"
};
var student = { firstName:"David", lastName:"Manual", age:20, hairColor:"black" };
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
delete object.property
delete object[property]
delete object.property delete object[property]
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
delete student.hairColor
delete student.hairColor
delete student.hairColor

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
delete student["hairColor"]
delete student["hairColor"]
delete student["hairColor"]

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
console.log(student.hairColor) //before: prints "color"
console.log(student.hairColor) //after: prints "undefined"
console.log(student.hairColor) //before: prints "color" console.log(student.hairColor) //after: prints "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