Javascript Object Properties

A Javascript properties are objects variables used to hold the specific value type. As its name says, this is simply property name declaration as string with any type of value assign to it. For example, the following object obj has a property whose name is the string "name" and it has value "Jimi". Similarly "age" is property name and "21" is value assigned to it.

Syntax

var Person = { name : "Jimi", age : 21 };

Adding New Property

In Javascript, you can add any number of property to the existing object. You need to give name of the new property and value assign to it. The below example creating new property "address" to the existing object "Person" with value as "12-13/A1". New "Person" object has three properties name, age and address.

Syntax

var Person = { name : "Jimi", age : 21 };
Person.address = "12-13/A1";

Reading Property

In Javascript you can access or read object property via its name. If you see below example, it is accessing all three property of the "Person" object.

Syntax

document.write(Person.name);
document.write(Person.address);
document.write(Person.age);

Removing Property

In Javascript delete keyword is use to delete the existing property from object.

Syntax

var Person = { name : "Jimi", age : 21 };
delete Person.name;

Loop Through Property

You can loop through the object properties by using for..in loop to access all the properties.

Syntax

var Person = { name : "Jimi", age : 21 };
//Adding new propert
Person.address = "23";
//Looping object properties
for (var key in Person) 
{
    if (Person.hasOwnProperty(key))
    {
		document.write(key + " = " + p[key] + "</br>");
    }
}

Javascript Complete Object Example

<html>
<head>
<script type="text/javascript">
var Person = { name : "Jimi", age : 21 };

//Reading object properties
document.write(Person.name);
document.write(Person.age);
document.write("</br>");

//Adding new property to object
Person.address = "12-13/A12";
document.write(Person.address);
document.write("</br>");

//Removing property from Person object
delete Person.age;
document.write(Person.age);
document.write("<br/>");

//Looping object properties
for (var key in Person) 
{
    if (Person.hasOwnProperty(key))
    {
		document.write(key + " = " + Person[key] + "</br>");
    }
}
</script>
</head>
<body>
</body>
</html>