Objects in JavaScript | How to Create Objects

We know JavaScript is a simple object-based language. Everything is an object in JavaScript.

An object in JavaScript is an entity or any real-world thing that has a state and behavior.

Here, the state represents properties (characteristics) of an object and behavior represents actions or functionality of an object.

In the real world, everything in JavaScript is an object if it has properties and actions.

For example, a person is an object. He has properties like black hair, black eyes, fair skin, weight, etc., and actions like eat, sleep, walk, play, study, etc.

JavaScript object example

Other examples of objects are car, pen, bike, chair, glass, keyboard, monitor, etc.

Thus, an object in JavaScript is a programming abstraction that groups together a set of data and functions to create a model of something from the real world.

In other words, an object simply merges data and functions together into a single cohesive unit. The function works on the data placed together in a unit.

Object Properties in JavaScript


Object properties (or fields) define the characteristics of an object. For instance, a car has a size, model, weight, color, price, and many other attributes.

These characteristics are called fields or properties. An object’s properties simply store data related to an object. They are represented by variables in JavaScript that are used internally in the object’s methods.

Since they are visible globally, we can access variables throughout the page. The general syntax to access an object’s properties is as follows:

objectName.propertyName;
Or,
objectName["propertyName"];

Here, objectName is the name of an object, and propertyName is the name of property (data filed) of an object. Both are case-sensitive.

Consider an example where we will create an object named myCar and give it properties named make, model, color, price, and year as follows:

var myCar = new Object(); // Using Object constructor.
  myCar.make = "Indian";
  myCar.model = "HigherXLV";
  myCar.color = "Red";
  myCar.year = 2022;

Object Methods in JavaScript


Object methods are functions with which an object behaves. In other words, methods represent tasks that are associated with an object. They perform different actions, mostly on its own properties.

For example, a person might have functions like eat(), sleep(), study(), etc. The general syntax to call a method is as follows:

objectReference.methodName([arguments])

objectReference represents the name of the object, or any other reference. methodName represents the name of the method, and arguments are values that the method accepts.

Hence, we can say that an object is a named collection of variables and functions.

Let’s understand the concept of objects in JavaScript with the help of an example. A student is an object in JavaScript. It has five properties and one function (i.e. method).

var student = {
// Declaration of properties (variables).
   name: "John",
   schoolName: "RSVM",
   rollNo: 05,
// Declaration of methods.
   reading: function() {
        // function code
   },
   playing: function() {
       // function code
   }
 };

Note:

1. In the object student, name, schoolName, and rollNo are called keys. An object cannot have two or more keys with the same name because keys are used to access their corresponding values.

2. The values of properties can be a number, string, array, boolean, or even another object.

3. The value of method is always a function.

Thus, we can say that an object is a set of key/value pairs.

Ways for creating objects in JavaScript


JavaScript is template based, not class based. Here, we don’t create class to get the object. But, we direct create objects.

An object in JavaScript is the template from which we can make instances. In a purely object-oriented language like Java, an object is an instance made from a class.

We need to create a class before creating its object. Since JavaScript is a template-based, not class based, therefore, we do not need to create a class to get object. We can create objects in JavaScript directly.

There are three ways to create objects to manage enormous tasks and data sets within an application. They are as follows:

  • By object literal
  • By creating an instance of Object directly (using new keyword)
  • Using an object constructor (using new keyword)

Object Literal in JavaScript


The simplest and the most popular way to create an object in JavaScript is to use object literal. The general syntax to create an object literal is as follows:

var objectName = {
    propertyName1:value1,
    propertyName2:value2,
    propertyName3:value3,
    .
    .
    propertyNameN:valueN,
    functionName1: function() {
        // code for function
    },
    functionName2: function() {
       // code for function
    }
 };

This is a simple syntax of an object created using object literal format. As you can observe that we have created objects with curly braces where properties and values are separated by a colon (:).

The following code creates an empty object called myObject:

var myObject = { };

Here’s we can create an object with several properties by using object literal:

var person = {
// Declaration of properties of an object person.
   firstName: "John",
   lastName: "Herry",
   age: 25,
   skinColor: "White"
};

The preceding code example creates an object called person, which holds four properties: firstName, lastName, age, and skinColor.

The values contained in each property are “John”, “Herry”, 25, and “White” respectively. We could access the firstName property of the person object using dot notation like this:

document.write(person.firstName);

You can also write properties without double-quotes. To access a property of an object, the object name must be followed by a dot and the name of the property that we want.

Example Programs based on Object Literals


1. Let’s create an HTML program where we will create an object person and access the various properties and display them on browser’s window.

Program code 1:

<script>
  var person = {
      firstName:"John",
      lastName:"Herry",
      age: 25,
      skinColor:"White"
    };
 // Accessing properties of person object.
    document.write("First name: " +person.firstName+ "<br>");
    document.write("Last name: " +person.lastName+ "<br>");
    document.write("Age: " +person.age+ "<br>");
    document.write("Skin color: " +person.skinColor);
</script>
Output:
      First name: John
      Last name: Herry
      Age: 25
      Skin color: White

2. Let’s create a HTML program where we will create an object student and access the various properties of a student and display them on the browser’s window. Look at the systematic source code to understand better.

Program code 2:

<script>
  var student = {
      firstName:"John",
      lastName:"Herry",
      schoolName: "RSVM",
      rollNo: 05,
      age: 16,
      city: "Dhanbad",
      myfunction:function() {
           display();
      }
    };
    function display() {
 // Accessing properties of student object.
      document.write("First name: " +student.firstName+ "<br>");
      document.write("Last name: " +student.lastName+ "<br>");
      document.write("School name: " +student.schoolName+ "<br>");
      document.write("Roll no: " +student.rollNo+ "<br>");
      document.write("Age: " +student.age+ "<br>");
      document.write("City: " +student.city);
    }
    student.myfunction(); // Calling function using student object reference.
</script>
Output:
      First name: John
      Last name: Herry
      School name: RSVM
      Roll no: 5
      Age: 16
      City: Dhanbad

3. Let’s create an HTML program where we will perform the addition, subtraction, and multiplication of three numbers and display results obtained on the browser’s window.

Program code 3:

<script>
  var cal = {
        a: 25,
        b: 25,
        c: 25,
        addition:function() {
            sum = cal.a + cal.b + cal.c;
            document.write("Addition: " +sum+ "<br>");
        },
       subtraction:function() {
           sub = cal.a - cal.b - cal.c;
           document.write("Subtraction: " +sub+ "<br>");
       },
       multiplication:function() {
           multiply = cal.a * cal.b * cal.c;
           document.write("Multiplication: " +multiply);
       }
   };
    function display() {
       cal.addition();
       cal.subtraction();
       cal.multiplication();
    }
   display(); // Calling function.
</script>
Output:
     Addition: 75
     Subtraction: -25
     Multiplication: 15625

By Creating Instance of Object


We can create an object directly by using a combination of a new keyword and Object() constructor function.

The new keyword and object constructor create a blank object in which we can then add properties and methods to the object using dot notation.

Each statement that adds property and method to any object must end with a semicolon. The general syntax to create an object in JavaScript using a new keyword and Object() constructor is as follows:

var objectName = new Object();
objectName.propertyName1 = "Value1";
objectName.propertyName2 = "Value2";
objectName.propertyName3 = "Value3";
. . . . . .
objectName.functionName1 = function()
{ 
  // function code; 
};
objectName.functionName2 = function()
{ 
  // function code; 
};

Consider the following example.

var person = new Object();
// Adding properties to object person.
  person.name = "Herry";
  person.city = "Dhanbad";
  person.age = 25;
// Adding method to object person.
  person.display = function()
  {
     // function code;
  };

Let’s create a simple JavaScript program in which we will create an instance of Object using new keyword.

Program code 4:

<script>
 // Creating an instance of Object.
    var hotel = new Object();
 // Adding properties to the object hotel.
    hotel.name = "Park";
    hotel.rooms = 120;
    hotel.booked = 50;
 
// Adding functions to the object hotel.
    hotel.checkAvailability = function()
    {
       return this.rooms - this.booked;
    };
    hotel.display = function()
    {
       var hotelName = hotel.name; // Accessing name of hotel.
       document.write("Name of hotel: " +hotelName+ "<br>");
       var availableRooms = hotel.checkAvailability(); // Accessing function.
       document.write("Rooms left in hotel: " +availableRooms);
    };
    hotel.display();
</script>
Output:
      Name of hotel: Park
      Rooms left in hotel: 70

Creating Many Objects in JavaScript using Constructor Notation


Sometimes, we need to create several objects to represent similar things. In this situation, we can use the constructor function to create several objects in JavaScript.

For this, we need to create a function as a template with parameters. The argument values passed we can assign to parameters inside the current object by using this keyword.

In other words, we can set the properties inside the object with this keyword. The keyword this refers to the current object. We commonly used this keyword inside functions and objects.

For example, let us consider an employee object with properties like name, age, salary as given:

function employee(name, age, salary)
{
// Setting properties inside the object using this keyword.
   this.name = name;
   this.age = age;
   this.salary = salary;
}

In this example, we have created a function named employee that represents an object. But, we have used this keyword with properties that create a constructor.

We can use this keyword to assign values to the object’s properties based on the values passed to the function. To create an employee object with data, we have to create an object variable using new keyword as:

var emp = new employee("Micheal", 26, 35000);

The above statement creates emp and assigns the specified value for its properties. Now, the value of emp.name is the string “Micheal”, emp.age is the integer 26, and so on.

We can also create many employee objects with the help of new keyword. For example,

var emp1 = new employee("Tripti", 23, 60000);
var emp2 = new employee("Deep", 30, 65000);
var emp3 = new emplyee("Ivaan", 20, 25000);

1. Let us consider an example program where we will display the student details of the object student.

Program code 5:

// Code for creating Objects in JavaScript with Constructor functions.
<script>
  function Student()
  {
 // Properties of student.
    this.name = "Rashmi";
    this.cName = "SSLNT";
    this.rollNo = 05;
    this.city = "Dhanbad";
   }
   var st = new Student();
   document.write(st.name+ " " +st.cName+ " " +st.rollNo+ " " +st.city);
</script>

In this example, we have created a constructor function for Student object type. We have assigned values to the properties of Student object using this keyword. After that, we have created a student object using new.


2. Let’s create a JavaScript program in which we will assign values to the object’s properties by passing values to the function. We will create objects using constructor functions.

Program code 6:

<script>
  function employee(name, cName, age, salary)
  {
 // Properties of employee.
     this.name = name;
     this.cName = cName;
     this.age = age;
     this.salary = salary;
   }
 // Creating objects of employee type.
   var emp = new employee("Ruchi", "TCS", 25, 60000);
   document.write(emp.name+ " " +emp.cName+ " " +emp.age+ " " +emp.salary, "<br>");

   var emp = new employee("Tripti", "IBM", 24, 65000);
   document.write(emp.name+ " " +emp.cName+ " " +emp.age+ " " +emp.salary, "<br>");
   
   var emp = new employee("Priya", "Wipro", 23, 55000);
   document.write(emp.name+ " " +emp.cName+ " " +emp.age+ " " +emp.salary, "<br>");
</script>
Output:
     Ruchi TCS 25 60000
     Tripti IBM 24 65000
     Priya Wipro 23 55000

Modifying Prototype Object


JavaScript provides an advanced language feature object prototype that allows us to add a property to all instances of a particular object. Let’s create a JavaScript program in which we will add a few more properties using prototype property.

Program code 7:

// JavaScript code for modifying prototype Object.
<script>
   function Student(name, sName, id)
   {
     this.name = name;
     this.sName = sName;
   }
   var st = new Student("Tripti", "RSVM");
   document.write("Name: " +st.name+ ", " +"School name: "+st.sName, "<br>");

// Adding more properties using prototype property.
   Student.prototype.id = 12345;
   Student.prototype.marks = 500;
   document.write("Id: " +st.id+ ", "+"Marks obtained: " +st.marks);
</script>
Output:
      Name: Tripti, School name: RSVM
      Id: 12345, Marks obtained: 500

Note: We can use object constructor method for creating objects in JavaScript. But, we consider it as an inferior way to create objects because of the following reasons.

1. In this method, we require more typing than object literal method.

2. Object constructor method does not perform as well in web browsers.

3. It is more difficult to read and understand than object literal method.


In this tutorial, you learned objects in JavaScript, object properties, and object methods in JavaScript. Hope that you will have understood how to create objects in JavaScript.
Thanks for reading!!!
Next ⇒ Types of Objects in JavaScript⇐ Prev Next ⇒