JavaScript 8 🧬 objects
Objects are a fundamental data structure in JavaScript used to store collections of key-value pairs. They can represent real-world entities or abstract concepts with properties (data) and methods (functions).
A Quick Look at the Examples
// 1. Object literal syntax
const person = {
name: 'Alice',
age: 30,
isStudent: false,
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
// 2. Object constructor
const person2 = new Object();
person2.name = 'Alice';
person2.age = 30;
person2.isStudent = false;
person2.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
// 3. Object.create()
const prototype = {
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
const person3 = Object.create(prototype);
person3.name = 'Alice';
person3.age = 30;
// Accessing properties
console.log(person.name); // "Alice"
console.log(person['age']); // 30
// Modifying and adding
person.age = 31; // Modify
person.city = 'New York'; // Add
// Deleting
delete person.isStudent;
// Checking existence
console.log('name' in person); // true
console.log(person.hasOwnProperty('age')); // true
// Iterating
for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(`${key}: ${person[key]}`);
}
}
// Object.keys() and Object.entries()
let keys = Object.keys(person);
console.log(keys);
let entries = Object.entries(person);
console.log(entries);
entries.forEach(([key, value]) => {
console.log(key + ": " + value);
});
a. Creating Objects
Objects are a fundamental data structure used to store collections of key-value pairs. They can represent real-world entities or abstract concepts with properties (keys) and methods (functions).
Almost all objects are instances of Object. A typical object inherits properties from Object.prototype.
Four Ways to Create Objects
| Method | Syntax | Best For |
|---|---|---|
| Object Literal | const obj = { } | Most common, simple objects |
| Object Constructor | const obj = new Object() | Rarely used (literal is simpler) |
| Object.create() | const obj = Object.create(proto) | Prototypal inheritance |
| Class Syntax (ES6+) | class Person { } | Creating multiple instances |
1. Object Literal Syntax (Recommended)
const person = {
name: 'Alice',
age: 30,
isStudent: false,
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
// Shorthand method syntax (ES6)
const person2 = {
name: 'Alice',
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
2. Object Constructor
const person = new Object();
person.name = 'Alice';
person.age = 30;
person.isStudent = false;
person.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
3. Object.create() — Prototypal Inheritance
const prototype = {
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
const person = Object.create(prototype);
person.name = 'Alice';
person.age = 30;
person.greet(); // "Hello, my name is Alice" (inherited from prototype)
4. Class Syntax (ES6+)
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const person = new Person('Alice', 30);
person.greet(); // "Hello, my name is Alice"
b. Access, Add, Modify, and Delete Object Properties
Accessing Properties
Two ways to access object properties:
| Notation | Syntax | When to Use |
|---|---|---|
| Dot notation | obj.property | When the key is a valid identifier |
| Bracket notation | obj['property'] | When the key has spaces, hyphens, or is dynamic |
const person = { name: 'Alice', age: 30 };
// Dot notation
console.log(person.name); // "Alice"
console.log(person.age); // 30
// Bracket notation
console.log(person['name']); // "Alice"
console.log(person['age']); // 30
// Bracket notation with dynamic keys
const key = 'name';
console.log(person[key]); // "Alice"
// Keys with special characters
const data = { 'first-name': 'Alice', 'last name': 'Smith' };
console.log(data['first-name']); // "Alice"
console.log(data['last name']); // "Smith"
Adding and Modifying Properties
const person = { name: 'Alice', age: 30 };
// Modify existing property
person.age = 31;
console.log(person.age); // 31
// Add new property
person.city = 'New York';
console.log(person.city); // "New York"
// Add with bracket notation
person['country'] = 'USA';
console.log(person.country); // "USA"
Deleting Properties
const person = { name: 'Alice', age: 30, isStudent: false };
// Delete a property
delete person.isStudent;
console.log(person.isStudent); // undefined
console.log('isStudent' in person); // false
// Note: delete only works on own properties
// It does NOT delete inherited properties
c. Check for Property Existence and Property Iteration
Checking Property Existence
| Method | Checks Own? | Checks Inherited? | Example |
|---|---|---|---|
in operator | ✅ Yes | ✅ Yes | 'name' in person |
hasOwnProperty() | ✅ Yes | ❌ No | person.hasOwnProperty('name') |
undefined check | ✅ Yes | ✅ Yes | person.name !== undefined |
const person = { name: 'Alice', age: 30 };
// 'in' operator — checks own AND inherited
console.log('name' in person); // true
console.log('toString' in person); // true (inherited from Object.prototype)
console.log('city' in person); // false
// hasOwnProperty() — checks own only
console.log(person.hasOwnProperty('name')); // true
console.log(person.hasOwnProperty('toString')); // false (inherited)
console.log(person.hasOwnProperty('city')); // false
// undefined check — simple but unreliable if value is undefined
console.log(person.name !== undefined); // true
console.log(person.city !== undefined); // false
Iterating with for…in
The for...in loop iterates over enumerable properties, including inherited ones.
const person = {
name: 'Alice',
age: 30,
greet: function() {
console.log('Hello');
}
};
// for...in — includes inherited properties
for (let key in person) {
console.log(key); // "name", "age", "greet"
}
// Use hasOwnProperty() to skip inherited properties
for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(`${key}: ${person[key]}`);
}
}
// name: Alice
// age: 30
// greet: function() { ... }
d. Object.keys(), Object.entries(), and More Methods
Object.keys()
Returns an array of the object’s own enumerable property names.
const person = {
name: 'Alice',
age: 30,
greet: function() {}
};
let keys = Object.keys(person);
console.log(keys); // ["name", "age", "greet"]
Object.values()
Returns an array of the object’s own enumerable property values.
let values = Object.values(person);
console.log(values); // ["Alice", 30, function() {}]
Object.entries()
Returns an array of [key, value] pairs.
let entries = Object.entries(person);
console.log(entries);
// [["name", "Alice"], ["age", 30], ["greet", function() {}]]
// Iterate with forEach
entries.forEach(([key, value]) => {
console.log(key + ": " + value);
});
// name: Alice
// age: 30
// greet: function() {}
Common Object Methods
| Method | Description | Example |
|---|---|---|
Object.keys(obj) | Array of keys | ["name", "age"] |
Object.values(obj) | Array of values | ["Alice", 30] |
Object.entries(obj) | Array of [key, value] pairs | [["name", "Alice"]] |
Object.assign(target, ...sources) | Copy properties | Object.assign({}, obj) |
Object.freeze(obj) | Make immutable | Object.freeze(person) |
Object.seal(obj) | Prevent add/delete | Object.seal(person) |
Object.create(proto) | Create with prototype | Object.create(prototype) |
Object.defineProperty(obj, prop, desc) | Define property with descriptor | Object.defineProperty(obj, 'x', { value: 1 }) |
Object.defineProperties(obj, props) | Define multiple properties | Object.defineProperties(obj, { ... }) |
Object.getOwnPropertyNames(obj) | All own property names | ["name", "age"] |
Object.getOwnPropertySymbols(obj) | Own symbol properties | [Symbol('id')] |
Object.isPrototypeOf(obj) | Check prototype chain | Object.prototype.isPrototypeOf(person) |
obj.propertyIsEnumerable(prop) | Check enumerability | person.propertyIsEnumerable('name') |
obj.toString() | String representation | "[object Object]" |
obj.toLocaleString() | Locale-aware string | "[object Object]" |
obj.valueOf() | Primitive value | "[object Object]" |
Practical Examples
const person = { name: 'Alice', age: 30, city: 'New York' };
// Object.keys()
console.log(Object.keys(person)); // ["name", "age", "city"]
// Object.values()
console.log(Object.values(person)); // ["Alice", 30, "New York"]
// Object.entries()
console.log(Object.entries(person));
// [["name", "Alice"], ["age", 30], ["city", "New York"]]
// Object.assign() — copy properties
const copy = Object.assign({}, person);
console.log(copy); // { name: 'Alice', age: 30, city: 'New York' }
// Spread operator (ES6) — another way to copy
const copy2 = { ...person };
console.log(copy2);
// Object.freeze() — make immutable
Object.freeze(person);
person.age = 99; // Silently fails (or throws in strict mode)
console.log(person.age); // 30
// Object.seal() — prevent add/delete
const sealed = { name: 'Bob' };
Object.seal(sealed);
sealed.age = 25; // ✅ Can modify existing
sealed.city = 'NYC'; // ❌ Cannot add
delete sealed.name; // ❌ Cannot delete
console.log(sealed); // { name: 'Bob', age: 25 }
// Object.defineProperty() — define with descriptor
const obj = {};
Object.defineProperty(obj, 'id', {
value: 42,
writable: false,
enumerable: false,
configurable: false
});
console.log(obj.id); // 42
obj.id = 99; // Silently fails
console.log(obj.id); // 42
console.log(Object.keys(obj)); // [] (not enumerable)
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Objects</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
color: #333;
line-height: 1.6;
}
h1 { color: #007bff; border-bottom: 3px solid #007bff; padding-bottom: 10px; }
h2 { color: #28a745; border-left: 4px solid #28a745; padding-left: 15px; margin-top: 30px; }
.demo-box {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin: 15px 0;
}
pre {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
line-height: 1.8;
}
.keyword { color: #569cd6; }
.string { color: #ce9178; }
.number { color: #b5cea8; }
.function { color: #dcdcaa; }
.comment { color: #6a9955; }
.boolean { color: #569cd6; }
#output {
background: #e9ecef;
padding: 15px;
border-radius: 8px;
margin-top: 15px;
min-height: 40px;
font-family: 'Courier New', monospace;
font-size: 0.85rem;
border-left: 4px solid #007bff;
white-space: pre-wrap;
}
</style>
</head>
<body>
<h1>JavaScript Objects</h1>
<div class="demo-box">
<h2>1. Creating Objects</h2>
<pre>
<span class="comment">// Object literal</span>
<span class="keyword">const</span> person = {
name: <span class="string">'Alice'</span>,
age: <span class="number">30</span>,
greet() {
console.log(<span class="string">`Hello, ${this.name}`</span>);
}
};
<span class="comment">// Object constructor</span>
<span class="keyword">const</span> person2 = <span class="keyword">new</span> <span class="function">Object</span>();
<span class="comment">// Object.create()</span>
<span class="keyword">const</span> person3 = <span class="function">Object.create</span>(prototype);
<span class="comment">// Class syntax</span>
<span class="keyword">class</span> <span class="function">Person</span> { }
</pre>
</div>
<div class="demo-box">
<h2>2. Access, Modify, Delete</h2>
<pre>
<span class="comment">// Access — dot notation</span>
console.log(person.name);
<span class="comment">// Access — bracket notation</span>
console.log(person[<span class="string">'age'</span>]);
<span class="comment">// Modify</span>
person.age = <span class="number">31</span>;
<span class="comment">// Add</span>
person.city = <span class="string">'New York'</span>;
<span class="comment">// Delete</span>
<span class="keyword">delete</span> person.isStudent;
</pre>
</div>
<div class="demo-box">
<h2>3. Property Existence</h2>
<pre>
console.log(<span class="string">'name'</span> <span class="keyword">in</span> person); <span class="comment">// true</span>
console.log(person.hasOwnProperty(<span class="string">'age'</span>)); <span class="comment">// true</span>
console.log(person.hasOwnProperty(<span class="string">'toString'</span>)); <span class="comment">// false (inherited)</span>
</pre>
</div>
<div class="demo-box">
<h2>4. Object.keys(), Object.entries()</h2>
<pre>
<span class="keyword">let</span> keys = <span class="function">Object.keys</span>(person);
console.log(keys); <span class="comment">// ["name", "age", "greet", "city"]</span>
<span class="keyword">let</span> entries = <span class="function">Object.entries</span>(person);
entries.forEach(([key, value]) => {
console.log(key + <span class="string">": "</span> + value);
});
</pre>
</div>
<div class="demo-box">
<h2>5. Live Output — Objects</h2>
<div id="output">Loading...</div>
</div>
<script>
// ============================================
// Objects — Live Demo
// ============================================
let results = [];
// 1. Create an object
const person = {
name: 'Alice',
age: 30,
isStudent: false,
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
results.push('📌 Creating Objects:\n');
results.push(' Object literal: ' + JSON.stringify({ name: person.name, age: person.age }));
results.push('');
// 2. Accessing properties
results.push('📌 Accessing Properties:\n');
results.push(' person.name → ' + person.name);
results.push(' person["age"] → ' + person['age']);
results.push(' person.greet() → ' + person.greet());
results.push('');
// 3. Modifying and adding
results.push('📌 Modifying and Adding:\n');
person.age = 31;
person.city = 'New York';
results.push(' After person.age = 31 → ' + person.age);
results.push(' After person.city = "NY" → ' + person.city);
results.push('');
// 4. Deleting
results.push('📌 Deleting Properties:\n');
results.push(' Before delete: isStudent = ' + person.isStudent);
delete person.isStudent;
results.push(' After delete: isStudent = ' + person.isStudent);
results.push('');
// 5. Checking existence
results.push('📌 Checking Existence:\n');
results.push(' "name" in person → ' + ('name' in person));
results.push(' "isStudent" in person → ' + ('isStudent' in person));
results.push(' person.hasOwnProperty("age") → ' + person.hasOwnProperty('age'));
results.push(' person.hasOwnProperty("toString") → ' + person.hasOwnProperty('toString'));
results.push('');
// 6. Iterating with for...in
results.push('📌 Iterating with for...in:\n');
for (let key in person) {
if (person.hasOwnProperty(key)) {
const value = typeof person[key] === 'function' ? '[Function]' : person[key];
results.push(' ' + key + ': ' + value);
}
}
results.push('');
// 7. Object.keys()
results.push('📌 Object.keys():\n');
let keys = Object.keys(person);
results.push(' ' + JSON.stringify(keys));
results.push('');
// 8. Object.values()
results.push('📌 Object.values():\n');
let values = Object.values(person);
results.push(' ' + JSON.stringify(values));
results.push('');
// 9. Object.entries()
results.push('📌 Object.entries():\n');
let entries = Object.entries(person);
entries.forEach(([key, value]) => {
const displayValue = typeof value === 'function' ? '[Function]' : value;
results.push(' ' + key + ': ' + displayValue);
});
results.push('');
// 10. Object.assign() and spread
results.push('📌 Object.assign() and Spread:\n');
const copy = Object.assign({}, person);
results.push(' Object.assign({}, person) → ' + JSON.stringify(Object.keys(copy)));
const spread = { ...person };
results.push(' { ...person } → ' + JSON.stringify(Object.keys(spread)));
results.push('');
// 11. Object.freeze()
results.push('📌 Object.freeze():\n');
const frozen = { name: 'Bob', age: 25 };
Object.freeze(frozen);
frozen.age = 99; // Silently fails
results.push(' After Object.freeze and frozen.age = 99 → ' + frozen.age);
results.push('');
// 12. Object.seal()
results.push('📌 Object.seal():\n');
const sealed = { name: 'Bob' };
Object.seal(sealed);
sealed.age = 25; // ✅ Allowed
sealed.city = 'NYC'; // ❌ Not allowed
delete sealed.name; // ❌ Not allowed
results.push(' sealed after seal + modifications → ' + JSON.stringify(sealed));
results.push('');
// 13. Array of objects (common pattern)
results.push('📌 Array of Objects:\n');
const users = [
{ id: 1, name: 'Alice', role: 'Admin' },
{ id: 2, name: 'Bob', role: 'User' },
{ id: 3, name: 'Carol', role: 'Editor' }
];
users.forEach(user => {
results.push(' #' + user.id + ' ' + user.name + ' (' + user.role + ')');
});
document.getElementById('output').textContent = results.join('\n');
</script>
</body>
</html>
Quick Reference
Creating Objects
| Method | Syntax | Example |
|---|---|---|
| Object literal | { } | const obj = { name: 'Alice' } |
| Constructor | new Object() | const obj = new Object() |
| Object.create() | Object.create(proto) | const obj = Object.create(proto) |
| Class | class Name { } | class Person { } |
Accessing Properties
| Notation | Syntax | Use Case |
|---|---|---|
| Dot | obj.property | Valid identifier keys |
| Bracket | obj['property'] | Dynamic keys, special characters |
Checking Existence
| Method | Own? | Inherited? |
|---|---|---|
'key' in obj | ✅ Yes | ✅ Yes |
obj.hasOwnProperty('key') | ✅ Yes | ❌ No |
obj.key !== undefined | ✅ Yes | ✅ Yes |
Object Methods
| Method | Description |
|---|---|
Object.keys(obj) | Array of keys |
Object.values(obj) | Array of values |
Object.entries(obj) | Array of [key, value] pairs |
Object.assign(target, ...sources) | Copy properties |
Object.freeze(obj) | Make immutable |
Object.seal(obj) | Prevent add/delete |
Object.create(proto) | Create with prototype |
Object.defineProperty(obj, prop, desc) | Define property with descriptor |
Object.getOwnPropertyNames(obj) | All own property names |
Object.getOwnPropertySymbols(obj) | Own symbol properties |
Best Practices
✅ Do This:
// Use object literal syntax
const person = { name: 'Alice', age: 30 };
// Use shorthand method syntax
const person2 = {
name: 'Alice',
greet() { return `Hello, ${this.name}`; }
};
// Use dot notation for simple keys
person.name;
// Use bracket notation for dynamic keys
const key = 'name';
person[key];
// Use hasOwnProperty() when iterating
for (let key in person) {
if (person.hasOwnProperty(key)) { }
}
// Use Object.keys() for iteration
Object.keys(person).forEach(key => {
console.log(key, person[key]);
});
❌ Don’t Do This:
// Don't use new Object() when literal works
const person = new Object(); // Use { }
// Don't use for...in without hasOwnProperty
for (let key in person) {
console.log(key); // May include inherited properties
}
// Don't use delete on arrays
delete arr[0]; // Use arr.splice(0, 1) instead
// Don't modify objects while iterating
for (let key in person) {
delete person[key]; // Unpredictable behavior
}
Pro Tip: Object literals ({}) are the most common and readable way to create objects — use them by default. Use Object.freeze() to make objects immutable, and Object.seal() to prevent adding/removing properties while allowing modifications. Remember: for...in iterates inherited properties too — always use hasOwnProperty() to filter them out, or use Object.keys() for a cleaner approach. And the spread operator ({ ...obj }) is a modern, concise way to copy objects!
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!