Delete Operator in Javascript
In this article, we will see how to delete properties from objects using the delete operator in javascript. The “new” operator is used to create new objects whereas the delete operator is used to delete properties from objects. Let’s see in detail with an example code.
The syntax for deleting property from objects
delete.objectname.propertyname;
Example code
var student1 = new object();
student1.roll = 1;
student1.name = "john";
document.write(student1.roll, "<br/>"); // 1
document.write(student1.name, "<br/>"); // john
delete.student1.roll;
document.write(student1.roll, "<br/>"); // undefined
- See the above code, we have created the object “student1”.
- Then we created the “roll” property for object “student1” and assigned the value “1”. And we created the “name” property for object “student1” and assigned the value “john”.
- If I want to display only roll of the student1, so we print “student1.roll”.
- Then I want to display only the name of the student1, so we print “student1.name”.
- To delete the property “roll” to the object “student1”, we should use the “delete” keyword and then put the object name and propertyname.
- We printed “student1.roll” after deleting the property, so it returns undefined.