JavaScript Object Properties

Properties are the most important part of any JavaScript object.

JavaScript properties

Properties refer to the values associated with a JavaScript object.

JavaScript objects are collections of unordered properties.

Properties can usually be modified, added, and deleted, but some properties are read-only.

Access JavaScript properties

The syntax to access an object's property is:

objectName.property           // person.age

or:

objectName["property]       // person["age"]

or:

objectName[expression]       // x = "age"; person[x]

The expression must evaluate to a property name.

Example 1

person.firstname + " is " + person.age + " years old.";

Try It Yourself

Example 2

person["firstname"] + " is " + person["age"] + " years old.";

Try It Yourself

JavaScript for...in loop

JavaScript for...in statement to iterate over an object's properties.

syntax

for (variable in object) {
    Code to be executed
}

for...in The code block in the loop will execute for each property.

Loop through an object's properties:

Example

var person = {fname:"Bill", lname:"Gates", age:62}; 
for (x in person) {
    txt += person[x];
}

Try It Yourself

Add new property

You can add new properties to an existing object by simple assignment.

Assuming the person object already exists - then you can add new properties for it:

Example

person.nationality = "English";

Try It Yourself

You cannot use reserved words as property names (or method names). Please use JavaScript naming conventions.

Remove property

delete Remove properties from an object:

Example

var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"};
delete person.age;   // Or delete person["age"];

Try It Yourself

delete Keywords will delete both the value and the property itself.

After deletion, the property cannot be used until it is added back.

delete Operators are designed for object properties. They have no effect on variables or functions.

delete Operators should not be used for predefined JavaScript object properties. This will cause the application to crash.

Attribute Value

All properties have names. In addition, they have values.

The value is one of the properties of an attribute.

Other attributes include: enumerable, configurable, writable.

These attributes define how properties are accessed (are they readable or writable?).

In JavaScript, all properties are readable, but only the values are modifiable (only when the property is writable).

(ECMAScript 5 has methods to get and set all property attributes)

Prototype Properties

JavaScript objects inherit their prototype's properties.

delete Keywords do not delete inherited properties, but if you delete a prototype property, it will affect all objects that inherit from the prototype.