Loading

Object

  • In JavaScript object is a real-world entity having properties like states and behavior.
  • An object is used to store and organize data using a key-value pair structure.

Creating an object in JavaScript:

There are 3 ways to create an object in JavaScript:

  • Using object literal notation
  • Using a new keyword(by creating an instance of an object directly)
  • Using Object Constructor (new keyword).

Using Object literal notation

  • The simplest way to create an object is by using object literal notation.
  • object's properties and values are defined inside curly braces {}.

Syntax:

var person = {
    firstName: "John",
    lastName: "Doe",
    age: 30
};

Example:

<html>

<body>
  <script>
    emp = { id: 102, name: "Shyam Kumar", salary: 40000 }
    document.write(emp.id + " " + emp.name + " " + emp.salary); 
  </script>
</body>

</html>

Output:

102 Shyam Kumar 40000


Using a new keyword(by creating an instance of an object directly)

Syntax:

var objectname=new Object();

Example:

<html>

<body>
  <script>
    var emp = new Object();
    emp.id = 101;
    emp.name = "Ravi Malik";
    emp.salary = 50000;
    document.write(emp.id + " " + emp.name + " " + emp.salary); 
  </script>
</body>

</html>

Output:

101 Ravi Malik 50000


Using Object Constructor (new keyword)

  • You can create an object using the object constructor.

Syntax:

var person = new Object();
person.firstName = "John";
person.lastName = "Doe";

Example:

<html>

<body>
  <script>
    function emp(id, name, salary) {
      this.id = id;
      this.name = name;
      this.salary = salary;
    }
    e = new emp(103, "Vimal Jaiswal", 30000);
    document.write(e.id + " " + e.name + " " + e.salary); 
  </script>
</body>

</html>

Output:

103 Vimal Jaiswal 30000