How to create a custom object in JavaScript?

JavaScript offers multiple ways to create custom objects. Each method has its own syntax and use cases, making JavaScript flexible for object-oriented programming.

Method 1: Using Object Constructor

The new Object() constructor creates an empty object that you can populate with properties:

<!DOCTYPE html>
<html>
  <body>
    <p id="test1"></p>
    <script>
      var dept = new Object();
      dept.employee = "Amit";
      dept.department = "Technical";
      dept.technology = "Java";

      document.getElementById("test1").innerHTML =
        dept.employee + " is working on " + dept.technology + " technology.";
    </script>
  </body>
</html>
Amit is working on Java technology.

Method 2: Using Object Literal (Recommended)

Object literals provide a cleaner, more concise syntax for creating objects:

<!DOCTYPE html>
<html>
  <body>
    <p id="test2"></p>
    <script>
      var dept = {
        employee: "Sarah",
        department: "Marketing",
        technology: "Analytics",
        getInfo: function() {
          return this.employee + " works in " + this.department + " department.";
        }
      };

      document.getElementById("test2").innerHTML = dept.getInfo();
    </script>
  </body>
</html>
Sarah works in Marketing department.

Method 3: Using Constructor Function

Constructor functions allow you to create multiple objects with the same structure:

<!DOCTYPE html>
<html>
  <body>
    <p id="test3"></p>
    <script>
      function Department(employee, dept, tech) {
        this.employee = employee;
        this.department = dept;
        this.technology = tech;
        this.displayInfo = function() {
          return this.employee + " specializes in " + this.technology;
        };
      }

      var dept1 = new Department("John", "Development", "React");
      var dept2 = new Department("Lisa", "QA", "Automation");

      document.getElementById("test3").innerHTML = 
        dept1.displayInfo() + "<br>" + dept2.displayInfo();
    </script>
  </body>
</html>
John specializes in React
Lisa specializes in Automation

Comparison

Method Syntax Best For
Object Constructor new Object() Simple, single objects
Object Literal {key: value} Most common, clean syntax
Constructor Function function Constructor() Multiple similar objects

Conclusion

Object literals are the most popular method for creating custom objects due to their clean syntax. Use constructor functions when you need to create multiple objects with the same structure.

Updated on: 2026-03-15T22:09:23+05:30

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements