JavaScript Object Properties in Web Pages

JavaScript objects are elements with properties and values. A JavaScript Object can be anything. It can be a variable of a primitive data type or a user defined data type. JavaScript Object Properties are features that characterize the object.

Objects consist of properties used to describe it. A JavaScript object is a collection of properties of a specific object. You can modify properties , add new ones or remove them.

An object in JavaScript is created just like a variable. To create an object you have to use var keyword and the properties and assign values.  An object in JavaScript can be created using new keyword.  

Declaring Properties

Object properties are declared using dot operator (.) between object name and the property name . You can also declare as property-name:property-value pairs enclosed in curly brackets.

Syntax

var object-name={property-name:property-value, ….};

Syntax

var object-name= new Object();
object-name.property-name=property-value;

These examples explain ways in which the properties can be defined for a JavaScript Object.

Example

var vehicle={make:"Datsun", engine:" 125mph",seats:"5"};

Example

var vehicle= new Object();
vehicle. make="Datsun";
vehicle. engine=" 125mph";
vehicle.seats=5;

Accessing Object Properties

You can access object properties in two ways. By using the dot operator with object name or object name followed by property name in square brackets. It is  Similar to accessing an element of an array, not with an index but with a property name.

Syntax

objectName.propertyName

Syntax

objectName['propertyName']

This example demonstrates how to access property named make of an object named as vehicle.

var x = vehicle.make;
var y = vehicle['make'];
var course = {name: "JS", lessons: 41};
document.write(course.name.length);
var v1 = new vehicle("Datsun", 5, "125mph");
var v2 = new person("Beetle", 2, "100mph");

To access the object’s properties you can use the dot operator syntax.

function vehicle (make, seats) {
  this.make = make;
  this.seats = seats;
}
var veh1 = new vehicle ("Lester", 3);
var veh2 = new vehicle ("Concerta", 4);

Sample HTML and JavaScript Code

In the example below for..in loop is used to access the properties of the JavaScript Object and append the properties values in a string. The string thus created in displayed in the paragraph with id test.

<!DOCTYPE html>
<html>
<body>

<h2>Display Vehicle Properties</h2>

<p id="test"></p>

<script>
var msg = "";
var vehicle = {make:"Datsun", engine:"125mph", seats:5}; 
var prp;
for (prp in vehicle) {
  msg += vehicle[prp] + ", ";
}
document.getElementById("test").innerHTML = msg;
</script>

</body>
</html>

Output

JavaScript Object Properties Example

This way you can declare your required objects in JavaScript code and access the object properties .

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *