JavaScript Objects

JavaScript is a functional language and it's supporting objects too. Objects are generally used as a data structue likewise C# supports class. In this lession we will see how to use objects in JavaScript to store the value. Objects can have multiple properties. We will see the object oriented JavaScript in later lession.

To define the object we uses curly braces {}. For example

Example
var simpleObject = {};  // It will define an empty object without any propeties.
var addressObject = { 
	Country : "USA"
}
// It will define object with 1 property 

What are the properties we are defining inside the object are also called member of an object. Now we will see how to access those member's value from object.

Accessing Member

Members can be accessed using the big brackets operator [], similar like an array and it can be accessed by period operator '.' [dot]. While accessing member of an object we need to provide the name of the member. For exmple

Example
var country = addressObject["Country"]; // It will return the value "USA"
var country = addressObject.Country;    // It will also return the value "USA" 

When we are using period operator then member name should not contain any spaces in between or it must not start with any illegal characters or any number. In above code snippet we have seen how we can access the member to get the value, similarly we can assign value to member of an object in same way, For example

Example
addressObject["State"] = "New York";    // It will set value for State member
addressObject.Pin = "xyz";  // It will set value for Pint member

Iterating in object

If we want to access all the member of an oject then we need to iterate in an object. Before accessing any element we need to check whether that member exists in object or not, if member is not exist in object then it will thrown an error, so it's always good practice to check before accessing object member. For example

Example
var addressObject = { 
	Country : "USA"
} 
addressObject["State"] = "New York";	
addressObject.Pin = "xyz";

for (var property in addressObject)
{ 
    if (addressObject.hasOwnProperty(property)) 
    { 
        console.log("The Property Name: " + property + ", The value is: " + addressObject[property]) 
    } 
} 
 
/* 
The above code snippet will print the output as below 
The Property Name: Country, The value is: USA 
The Property Name: State, The value is: New York 
The Property Name: Pin, The value is: xyz 
*/ 

 

← Previous

Next →