Object in JavaScript-tutorial
In JavaScript, an object is like a real-world entity that has properties (state) and behaviors (methods).
Objects help store and organize data in a key-value pair format, making your code cleaner and more flexible.
Objects help store and organize data in a key-value pair format, making your code cleaner and more flexible.
Creating Objects in JavaScript
There are three main ways to create an object
Using Object Literal Notation
This is the simplest and most common way.
You directly define the object inside curly braces {}.
Syntax:
There are three main ways to create an object
- Using Object Literal Notation
- Using the new keyword (direct instance)
- Using Object Constructor
Using Object Literal Notation
This is the simplest and most common way.
You directly define the object inside curly braces {}.
Syntax:
var person = { firstName: "John", lastName: "Doe", age: 30};
Example:
<!DOCTYPE html><html>
<body> <script> var emp = { id: 102, name: "Shyam Kumar", salary: 40000 }; document.write(emp.id + " " + emp.name + " " + emp.salary); </script></body>
</html>
Output
.webp)
Using new keyword (direct instance)
You can also create an object by instantiating object directly.
Syntax:
var objectName = new Object();
Example:
<!DOCTYPE html><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
.webp)
Using Object Constructor
This method uses a constructor function to create multiple similar objects.
Syntax:
function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age;}var p = new Person("John", "Doe", 30);
Example:
<!DOCTYPE html><html>
<body> <script> function emp(id, name, salary) { this.id = id; this.name = name; this.salary = salary; } var e = new emp(103, "Vimal Jaiswal", 30000); document.write(e.id + " " + e.name + " " + e.salary); </script></body>
</html>
Output
.webp)
Objects are one of the most powerful features in JavaScript, used for modeling real-world data and building complex applications easily.