JavaScript Objects

JavaScript Objects

A JavaScript object is a variable which stores multiple data in the form of key and value pairs separated by a colon.

This key (or name) value pair together is called property of an object.

Example: An object with Employee Data

var person = {firstName: “Priyanka”, lastName: “Pandey”, age: 22, education:”MCA”};

Creating an Object

We can create an object using given three ways:

  1. Using Object Initializers
    In this method of object creation, we directly create a variable and define it like an object with key and value pair.

    var obj = {key1: “value1”, key2: “value2”, …..., keyN: “valueN”};
    var person = {firstName: “Hitesh”, lastName: “Goel”, age: 23}

     

or, simply by defining a variable and assigning it an empty object as shown below:

var obj = {};
  1. Using a constructor function
    In this method of object creation, we follow given two steps:

    1. We define the object type by writing a constructor function.
    2. Create an instance of the object with new.

Example: An object person with its properties

Constructor Function

function employee(firstName, lastName, dob) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.dob = dob;
}

Instance of the Constructor

var person = new employee('Aditya', 'Farrad', 1994);

In the above example, we have created a JavaScript function and named it employee. Then for every new object creation, we will call this function with the values. Here the keys are fixed as firstName, lastName and dob. this in the function is a JavaScript keyword which refers to the current object.

 

  1. Using the create method

This method creates a new object using an existing object as a prototype.

var newPerson = Object.create(person);

Here, we have created a new object newPerson using the object person created in the method 1 above as a prototype.

Access an element of an Object

We can access an element [in case of object, property] of an object in given two ways:

  1. propertyName

Example: person.firstName;

  1. objectName[“propertyName”]

Example: person[“firstName”];

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.