JavaScript Object Properties
JavaScript में Object Properties वे values होती हैं जिन्हें हम object में keys के माध्यम से store और access करते हैं।
हर property का एक नाम (key) और एक मान (value) होता है।
इस अध्याय में आप सीखेंगे:
- Object Properties क्या होती हैं
- Properties को access, update, add और delete कैसे करते हैं
- Bracket vs Dot Notation
- Property names में rules
- अभ्यास प्रश्न
Object Property क्या होती है?
Object में हर key-value pair को एक property कहा जाता है।
Example:
let person = {
name: "Ravi",
age: 28
};
यहाँ name
और age
दो properties हैं, जिनकी values "Ravi"
और 28
हैं।
Object Property को Access करना
🔹 1. Dot Notation (साधारण और तेज़ तरीका):
console.log(person.name); // Output: Ravi
console.log(person.age); // Output: 28
🔹 2. Bracket Notation (जब key dynamic हो):
console.log(person["name"]); // Ravi
let prop = "age";
console.log(person[prop]); // 28
Bracket notation तब use होता है जब:
- Key variable में हो
- Key में space या special character हो
जैसे:person["full name"]
Object Property को Add करना
person.city = "Delhi"; // Dot notation
person["gender"] = "male"; // Bracket notation
Object Property को Update करना
person.age = 30;
Object Property को Delete करना
delete person.age;
Property Names में Rules
- Property नाम string (या symbol) होना चाहिए
- Valid identifiers हों तो dot notation चलेगा
- Invalid identifiers (जैसे space, dash) हों तो bracket notation ज़रूरी है
Example:
let book = {
"book-title": "JavaScript Guide",
"author name": "Amit"
};
console.log(book["book-title"]); // ✅
console.log(book["author name"]); // ✅
// console.log(book.book-title); ❌ Error
Object के अंदर Property Check करना
🔹 in
Operator:
"age" in person; // true
"salary" in person; // false
🔹 hasOwnProperty()
Method:
person.hasOwnProperty("name"); // true
Object.keys()
, Object.values()
, Object.entries()
let user = {
name: "Neha",
age: 22
};
console.log(Object.keys(user)); // ["name", "age"]
console.log(Object.values(user)); // ["Neha", 22]
console.log(Object.entries(user)); // [["name", "Neha"], ["age", 22]]
Computed Properties (Dynamic Key)
let key = "email";
let user = {
[key]: "neha@example.com"
};
console.log(user.email); // Output: neha@example.com
अभ्यास प्रश्न
- Object में property क्या होती है?
- Dot और Bracket Notation में क्या अंतर है? उदाहरण सहित।
- किसी property को update और delete कैसे करेंगे?
- नीचे दिए गए code का output बताइए:
let person = { name: "Amit", age: 35 }; delete person.age; console.log("age" in person);
Object.entries()
क्या return करता है? एक उदाहरण दीजिए।