JavaScript Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 2.10

Adding and Deleting Object Own Properties

This section provides a quick description of object's own properties. A tutorial example is provided on how to add, update, and delete object's own properties.

When you create a new object from the "Object" constructor, you will get an object with only two default properties:

  • "constructor" - This property contains the constructor function of this object.
  • "prototype" - This property represents the prototype of this object to allow you to modify the prototype on the fly.

But you can add more properties to one object at any time using an assignment operation like this:

object_name.property_name = initial_value;

The added property is for this one object only. Other objects will not have this property.

You can also delete properties from one object at any time using a delete operation like this:

delete object_name.property_name;

Here is a tutorial example that shows you how to add a new property, update the property value, retrieve the property value, and delete a property.

<html>
<!-- Object_Property.html
   Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Object Properties of "Object"</title>
</head>
<body>
<pre>
<script type="text/javascript">

   // Creating objects of "Object" type
   var mySite = new Object();
   var myBook = new Object();
   
   // Adding a new property to one object only
   mySite.url = "herongyang.com";
   myBook.author = "Herong Yang";

   // Updating a property value
   mySite.url = "www.herongyang.com";

   // Showing property values
   document.writeln('mySite.url: '+mySite.url);
   document.writeln('myBoot.url: '+myBook.url);
   document.writeln('mySite.author: '+mySite.author);
   document.writeln('myBook.author: '+myBook.author);

   // Is this property for one object only?
   document.writeln('mySite.hasOwnProperty("url"): '
      +mySite.hasOwnProperty("url"));

   // Deleting a property from one only
   document.writeln('Deleting mySite.url...');
   delete mySite.url;
   document.writeln('mySite.url: '+mySite.url);
</script>
</pre>
</body>
</html>

The result matches my expectation:

mySite.url: www.herongyang.com
myBoot.url: undefined
mySite.author: undefined
myBook.author: Herong Yang
mySite.hasOwnProperty("url"): true
Deleting mySite.url...
mySite.url: undefined

Sections in This Chapter

What Is an Object?

Objects of "Object" Data Type

Adding and Deleting Object Own Properties

Adding and Deleting Object Own Methods

Using "this" Keyword to Represent Current Object

Object Literals of the "Object" Type

Objects and Associate Arrays

Objects with Indexed Properties

Differences between "Object" and "Array"

Using "Array" Objects as "Object" Objects

Dr. Herong Yang, updated in 2008
Adding and Deleting Object Own Properties