JavaScript Objects

As you know that the JavaScript language is totally based on objects.

In JavaScript, you have the following two options to create an object:

A direct instance of an object in JavaScript, is created by using the new keyword. Here is the general form shows how to create an object in JavaScript by creating a direct instance of object:

Obj = new object();

You are free to add properties and methods to an object in JavaScript, just by using the dot (.) followed by a property or method name as shown in the below code fragment:

Obj.name="Deepak";
Obj.branch="CSE";
Obj.rollno=15;
Obj.getValue();

From the above code fragment, Obj is the newly created object, name, branch, and rollno are its properties, and getValue() is its method.

You will learn all about Object in JavaScript divided into the following tutorials:

JavaScript Object Example

The values are written in name:value pairs (name and value separated by a colon). Here is an example of object in JavaScript

<!DOCTYPE html>
<html>
<head>
   <title>JavaScript Object Example</title>
</head>
<body>

<p id="object_para1"></p>
<p id="object_para2"></p>
<script>
   var object_var = {firstName:"Aman", lastName:"Tripathi", age:19, eyeColor:"black"};
   document.getElementById("object_para1").innerHTML = object_var.firstName + " is " + object_var.age + " years old.";
   document.getElementById("object_para2").innerHTML = "His eye's color is " + object_var.eyeColor + ".";
</script>

</body>
</html>

Here is the output produced by the above JavaScript Object example program.

javascript object

Here is the live demo output produced by the above Object example in JavaScript.

Access Object Properties in JavaScript

Here is an example shows how to access properties of object in JavaScript.

<!DOCTYPE html>
<html>
<head>
   <title>JavaScript Object Example</title>
</head>
<body>

<p id="object_para2"></p>
<script>
   var object_var2 = {
      firstName : "Aman",
      lastName : "Tripathi",
   };
   document.getElementById("object_para2").innerHTML = object_var2.firstName + " " + object_var2.lastName;
</script>

</body>
</html>

Here is the output produced by the above JavaScript object example.

javascript object example

Access Object Methods in JavaScript

Here is an example shows how to access methods of object in JavaScript.

<!DOCTYPE html>
<html>
<head>
   <title>JavaScript Object Example</title>
</head>
<body>

<p id="object_para3"></p>
<script>
   var object_var3 = {
      firstName: "Aman",
      lastName : "Tripathi",
      fullName : function(c) {
         return this.firstName + " " + this.lastName;
      }
   };
   document.getElementById("object_para3").innerHTML = object_var3.fullName();
</script>

</body>
</html>

You will watch the same output produced, as in the above example.

JavaScript Online Test


« Previous Tutorial Next Tutorial »