JS Objects

JS is an Object-Oriented Programming (OOP) language.

An OOP language allows us to define our own objects and make our own variable types.

Basically, an object is a special kind of data. It has properties and methods. See the examples below.

 

Example 1

<html>
<body>

<h3>JS Objects</h3>

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

<script>
//creating an object with some properties
var student = {
firstName: "Sandip",
lastName: "Sharma",
roll: 20,
stream: "CSE"
};

//displaying data from the object
document.getElementById("test").innerHTML =
student.firstName + " is from " + student.stream + " with " + student.roll + ".";
</script>

</body>
</html>

 

Output:

JS Objects

Sandip is from CSE with 20.

 

Example 2

<html>
<body>

<h3>JS Objects</h3>

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

<script>
//creating an object with some properties and method
var student = {
//properties
firstName: "Sandip",
lastName: "Sharma",
roll: 20,
stream: "CSE",
//method
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

//displaying data from the object
document.getElementById("test").innerHTML =
student.fullName() + " with roll number " + student.roll + " is from Dept. of " + student.stream + ".";
</script>

</body>
</html>

 

Output:

JS Objects

Sandip Sharma with roll number 20 is from Dept. of CSE.