Object properties

Description

Object properties are data value grouped into object.

Example

The following code shows how to access properties via bracket notation.


var tutorial = {
   name : "JavaScript",
   pageSize : 9 /*  w w  w .j  a va2 s  . c  o  m*/
}; 
console.log(tutorial["name"]); //"JavaScript" 
console.log(tutorial.name); //"JavaScript" 

The code above generates the following result.

Example 2

The following code uses variables for property access.


var tutorial = {
   name : "JavaScript",
   pageSize : 9 /*from  w  ww. j a v a2s  . c  o m*/
}; 

var propertyName = "name"; 
console.log(tutorial[propertyName]); //"JavaScript" 

The code above generates the following result.

Example 3

The following code uses bracket notation when the property name contains space:


var tutorial = {
    "tutorial name" : "JavaScript",
    pageSize : 9 //from   ww  w.ja v a 2s . c  o m
}; 
console.log(tutorial["tutorial name"]); 

The code above generates the following result.

Example 4

The for...in loop performs the statement for each property.


var myData = {
  name : "JavaScript",
  weather : "Good",
  printMessages : function() {/*from   w  w  w. java  2 s  . c  om*/
    console.log("Hello " + this.name + ". ");
    console.log(this.name +" is " + this.weather + ".");
  }
};

myData.printMessages();

for ( var prop in myData) {
  console.log("Name: " + prop + " Value: " + myData[prop]);
}

The code above generates the following result.

Example 5

A comma separates properties in an object literal. There is no need to add comma for the last property.

Property names can also be specified as strings or numbers:


var tutorial= {
   "name" : "JavaScript", 
   "pageSize" : 9,
   1: true //from  w  ww  .j a  va2 s. com
}; 
console.log(tutorial.name); //JavaScript
console.log(tutorial.pageSize); //9
console.log(tutorial["1"]); //

The code above generates the following result.

Example 6

Object literals can also be used to pass a large number of optional arguments to a function:


function displayInfo(args) { /* ww  w. j  a va 2s  . co m*/
    if (typeof args.name == "string"){ 
        console.log("Name: " + args.name); 
    } 
    if (typeof args.pageSize == "number") { 
        console.log("PageSize: " + args.age); 
    } 
} 
displayInfo({ 
      name: "JavaScript", 
      pageSize: 9 
}); 

displayInfo({ 
     name: "HTML" 
}); 

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions