In JavaScript, an object is a collection of key-value pairs (properties), where keys are strings (or Symbols) and values can be of any type (primitive, object, or function).
π Think of an object as a real-world entity that has properties (data) and methods (functions that operate on the data).
π Example:
let person = {
name: "Himanshu", // property (key: value)
age: 27,
isDeveloper: true,
greet: function() { // method
console.log("Hello, my name is " + this.name);
}
};
console.log(person.name); // Access property β "Himanshu"
person.greet(); // Call method β "Hello, my name is Himanshu"
π Key Points:
- Properties: Data stored in key-value pairs.
Example:name: "Himanshu" - Methods: Functions inside objects.
Example:greet: function() { ... } - Accessing values:
- Dot notation β
person.name - Bracket notation β
person["age"]
- Dot notation β
- Objects can store anything: numbers, strings, arrays, functions, or even other objects.
β
In short:
An object in JavaScript is a non-primitive data type used to group related data and functionality together.
Would you like me to also explain the different ways to create objects in JavaScript (e.g., using object literal, constructor, Object.create, class)?
You said:
How do you create an object?
In JavaScript, you can create an object in multiple ways depending on your use case. Letβs go step by step:
1. Object Literal (Most Common)
The simplest and most widely used method.
let person = {
name: "Himanshu",
age: 27,
isDeveloper: true
};
console.log(person.name); // "Himanshu"
2. Using new Object() Constructor
This uses JavaScriptβs built-in Object constructor.
let car = new Object();
car.brand = "Toyota";
car.model = "Innova";
car.year = 2024;
console.log(car.brand); // "Toyota"
3. Using a Constructor Function
Useful for creating multiple similar objects.
function Person(name, age) {
this.name = name;
this.age = age;
}
let user1 = new Person("Himanshu", 27);
let user2 = new Person("Rahul", 30);
console.log(user1.name); // "Himanshu"
4. Using Object.create()
Creates a new object with a specified prototype.
let animal = {
type: "Mammal",
eat: function() {
console.log("Eating...");
}
};
let dog = Object.create(animal);
dog.breed = "Labrador";
console.log(dog.type); // "Mammal" (inherited)
5. Using ES6 class Syntax
A modern way (syntactic sugar over constructor functions).
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log("Hello, I'm " + this.name);
}
}
let user = new Person("Himanshu", 27);
user.greet(); // "Hello, I'm Himanshu"
β Summary:
- Object Literal β Best for single objects.
new Object()β Rarely used, not recommended.- Constructor Function β For creating many similar objects (old way).
Object.create()β For prototype-based inheritance.- Class (ES6) β Modern, clean, recommended for OOP style.
