Object Definitions in JavaScript
Object Definitions in JavaScript
What is an Object?
An object in JavaScript is a collection of key-value pairs.
Keys are called properties.
Values can be any data type including other objects or functions (called methods).
How to Define Objects
1. Using Object Literals (most common)
const person = { name: "John", age: 30, greet: function() { console.log("Hello, " + this.name); }};2. Using the new Object() Syntax
const person = new Object();person.name = "John";person.age = 30;person.greet = function() { console.log("Hello, " + this.name);};3. Using a Constructor Function
function Person(name, age) { this.name = name; this.age = age; this.greet = function() { console.log("Hello, " + this.name); };}const person1 = new Person("John", 30);4. Using ES6 Classes (syntactic sugar over constructor functions)
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log("Hello, " + this.name); }}const person1 = new Person("John", 30);Accessing Object Properties
console.log(person.name); // Dot notationconsole.log(person["age"]); // Bracket notationAdding or Modifying Properties
person.city = "New York";person["country"] = "USA";Summary
| Definition Method | Description |
|---|---|
| Object Literal | { key: value } |
new Object() | new Object() then add properties |
| Constructor Function | Function used with new keyword |
| ES6 Class | Modern syntax for constructor + methods |
Need help with specific object patterns or advanced object concepts like prototypes?