What is an Object?
A JavaScript object is a collection of properties (key-value pairs) that stores related data and functions
Simple: Like a real object (e.g., a car)
has properties (color, model, speed)
and
actions (drive, stop)
Basic Structure:
const person = {
name: "Raja",
age: 27,
city: "Madurai"
};
Syntax breakdown:
- {} = curly braces (object literal)
- key: value = property (key-value pair)
- : = separates key and value
- , = separates properties
Key Concepts
1. Properties (Key-Value Pairs)
| Term | Meaning |
|---|---|
| Key | Property name (e.g., name, age) |
| Value | Property data (e.g., "Raja", 27) |
| Property | Full key-value pair together |
Example:
const student = {
name: "Bala", // name = key, "Bala" = value
roll: 101, // roll = key, 101 = value
passed: true // passed = key, true = value
};
Values can be ANY data type:
const data = {
string: "hello", // string
number: 42, // number
boolean: true, // boolean
null: null, // null
array: [1, 2, 3], // array
object: { x: 10 }, // another object
function: function() { console.log("hi"); } // function
};
2. Methods (Functions as Properties)
When a property value is a function, it's called a method
Example:
Creating Objects (6 Ways)
1. Object Literal (Best/Most Common)
const person = {
name: "Raja",
age: 20
};
Best for: Readability, simplicity, speed
2. Using new Object()
const person = new Object();
person.name = "Raja";
person.age = 20;
3. Object Constructor
function Person(name, age) {
this.name = name;
this.age = age;
}
const p1 = new Person("Raja", 20);
4. Using Object.create()
const personTemplate = {
greet() { console.log("Hello!"); }
};
const person = Object.create(personTemplate);
person.name = "Raja";
5. Using Object.assign()
const person = Object.assign(
{},
{ name: "Raja" },
{ age: 20 }
);
6. Using Object.fromEntries()
const person = Object.fromEntries([
["name", "Raja"],
["age", 20]
]);

Top comments (0)