Objects in JavaScript are collections of **key-value pairs** (properties). The most common way is the **object literal** `{}`. **Object.create()** allows setting the prototype directly. **Classes** and **constructor functions** create objects with shared prototype methods.
1Understanding Creating Objects
Objects in JavaScript are collections of key-value pairs (properties). The most common way is the object literal {}. Object.create() allows setting the prototype directly. Classes and constructor functions create objects with shared prototype methods.
Use object literals {} for simple data. Use classes when you need multiple instances with shared methods.
// Object literal
const person = {
name: 'Alice',
age: 30,
greet() { return `Hi, I'm ${this.name}`; }
};
console.log(person.greet()); // Hi, I'm Alice
// Shorthand properties
const name = 'Bob', age = 25;
const bob = { name, age }; // { name: 'Bob', age: 25 }2Practical Example
Here is a real-world application of Creating Objects showing how it is used in production JavaScript code.
// Object.assign to merge objects
const defaults = { theme: 'light', lang: 'en', debug: false };
const userPrefs = { theme: 'dark', lang: 'fr' };
const config = Object.assign({}, defaults, userPrefs);
console.log(config);3Best Practices
Follow these guidelines when working with Creating Objects:
1. Use shorthand property names: { name } instead of { name: name }
2. Use computed property names: { [key]: value }
3. Prefer Object.freeze() for immutable configuration objects
Tip: Use object literals {} for simple data. Use classes when you need multiple instances with shared methods.
// Object literal
const person = {
name: 'Alice',
age: 30,
greet() { return `Hi, I'm ${this.name}`; }
};
console.log(person.greet()); // Hi, I'm Alice
// Shorthand properties
const name = 'Bob', age = 25;
const bob = { name, age }; // { name: 'Bob', age: 25 }