Objects
JavaScript Objects
In JavaScript, Object is a non-primitive data type. Mainly, it is defined as a data that is a collection of names, keys, and values.
The name: value pair consists of properties that have data types of strings, numbers, and Booleans.
Objects are used to store keyed collections of various types of data.
In JavaScript, variables are defined as containers which are used to store data values. But variables or arrays are not sufficient to fulfill needs of the real-time events.
So, JavaScript allows creating objects that act like real-time objects, with the help of methods and properties it makes programming easier to store and manipulate data.
Objects can be created with figure brackets {…} with a list of properties. A property is a “key: value” pair, where the key is a string, and value can be anything.
Syntax
var objname = {key1: value1, key2: value2, keyN: valueN};
Property and value are separated by colon (:)
For example,
var student = { Name: “Rahul” , Age: 22 , Subject: Commerce };
Code:
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
var student =
{
name : "John",
age : 22,
subject : "Commerce"
};
document.getElementById("demo").innerHTML =
student.name + " is " + student.age + " years old has " + student.subject + " Subjects. ";
</script>
</body>
</html>
Here, objname is defined as a student, where keys are named as name, age, and subject, property values are named as John, 22, Commerce and strings must be written within quotes but not numbers.
Further, in order to access the objects, we use syntax as objname.keyname.
Output: