JavaScript Objects & Properties
Learn to create and manipulate objects, understand properties, and master object-oriented programming in JavaScript. This is a foundational concept in programming and web interactivity that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world JavaScript experience. Take your time with each section and practice the examples
Object Fundamentals
Objects are the fundamental building blocks of JavaScript. They are collections of key-value pairs that can represent real-world entities, data structures, or any complex data.. This is an essential concept that every JavaScript developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Object Creation Methods
- Object Literals: Direct object creation with {}
- Constructor Functions: Create objects with 'new' keyword
- Object.create(): Create objects with specific prototype
- Class Syntax: Modern ES6+ class-based approach
- Factory Functions: Functions that return objects
Object Creation Examples
// 1. Object Literals (Most Common)
const person = {
name: "John Doe",
age: 30,
email: "john@example.com",
greet() {
return `Hello, my name is ${this.name}`;
}
};
console.log(person.name); // "John Doe"
console.log(person.greet()); // "Hello, my name is John Doe"
// 2. Constructor Functions
function Person(name, age, email) {
this.name = name;
this.age = age;
this.email = email;
this.greet = function() {
return `Hello, my name is ${this.name}`;
};
}
const john = new Person("John Doe", 30, "john@example.com");
const jane = new Person("Jane Smith", 25, "jane@example.com");
console.log(john.greet()); // "Hello, my name is John Doe"
console.log(jane.greet()); // "Hello, my name is Jane Smith"
// 3. Object.create()
const personProto = {
greet() {
return `Hello, my name is ${this.name}`;
}
};
const alice = Object.create(personProto);
alice.name = "Alice Johnson";
alice.age = 28;
console.log(alice.greet()); // "Hello, my name is Alice Johnson"
// 4. Class Syntax (ES6+)
class PersonClass {
constructor(name, age, email) {
this.name = name;
this.age = age;
this.email = email;
}
greet() {
return `Hello, my name is ${this.name}`;
}
getAge() {
return this.age;
}
}
const bob = new PersonClass("Bob Wilson", 35, "bob@example.com");
console.log(bob.greet()); // "Hello, my name is Bob Wilson"
// 5. Factory Functions
function createPerson(name, age, email) {
return {
name,
age,
email,
greet() {
return `Hello, my name is ${this.name}`;
},
getAge() {
return this.age;
}
};
}
const charlie = createPerson("Charlie Brown", 40, "charlie@example.com");
console.log(charlie.greet()); // "Hello, my name is Charlie Brown"Object Properties & Methods
// Object property access
const user = {
firstName: "John",
lastName: "Doe",
age: 30,
"full name": "John Doe", // Property with spaces
address: {
street: "123 Main St",
city: "New York",
zipCode: "10001"
},
hobbies: ["reading", "coding", "gaming"],
greet() {
return `Hello, I'm ${this.firstName} ${this.lastName}`;
}
};
// Dot notation
console.log(user.firstName); // "John"
console.log(user.age); // 30
console.log(user.greet()); // "Hello, I'm John Doe"
// Bracket notation
console.log(user["firstName"]); // "John"
console.log(user["full name"]); // "John Doe" (for properties with spaces)
console.log(user["age"]); // 30
// Nested object access
console.log(user.address.city); // "New York"
console.log(user["address"]["city"]); // "New York"
// Array property access
console.log(user.hobbies[0]); // "reading"
console.log(user.hobbies.length); // 3
// Adding properties
user.email = "john@example.com";
user["phone"] = "555-1234";
console.log(user.email); // "john@example.com"
console.log(user.phone); // "555-1234"
// Deleting properties
delete user.age;
console.log(user.age); // undefined
// Checking if property exists
console.log("firstName" in user); // true
console.log("age" in user); // false
console.log(user.hasOwnProperty("firstName")); // true
console.log(user.hasOwnProperty("toString")); // false (inherited)Object Methods & This Context
// Object methods and 'this' context
const calculator = {
value: 0,
add(num) {
this.value += num;
return this;
},
subtract(num) {
this.value -= num;
return this;
},
multiply(num) {
this.value *= num;
return this;
},
divide(num) {
if (num !== 0) {
this.value /= num;
} else {
console.error("Cannot divide by zero");
}
return this;
},
getValue() {
return this.value;
},
reset() {
this.value = 0;
return this;
}
};
// Method chaining
const result = calculator
.add(10)
.multiply(2)
.subtract(5)
.divide(3)
.getValue();
console.log(result); // 5
// 'this' context issues
const user = {
name: "John",
greet() {
return `Hello, ${this.name}!`;
}
};
console.log(user.greet()); // "Hello, John!"
// 'this' context lost when method is assigned to variable
const greetFunction = user.greet;
console.log(greetFunction()); // "Hello, undefined!"
// Solutions for 'this' context
// 1. Arrow functions (lexical 'this')
const user2 = {
name: "Jane",
greet: () => {
return `Hello, ${this.name}!`; // 'this' refers to global scope
}
};
// 2. Bind method
const user3 = {
name: "Bob",
greet() {
return `Hello, ${this.name}!`;
}
};
const boundGreet = user3.greet.bind(user3);
console.log(boundGreet()); // "Hello, Bob!"
// 3. Call and Apply methods
const user4 = {
name: "Alice"
};
function greet(greeting) {
return `${greeting}, ${this.name}!`;
}
console.log(greet.call(user4, "Hi")); // "Hi, Alice!"
console.log(greet.apply(user4, ["Hello"])); // "Hello, Alice!"Practice Exercise: Objects
// Exercise: Create a Book Management System
// 1. Create a Book class
class Book {
constructor(title, author, year, isbn) {
this.title = title;
this.author = author;
this.year = year;
this.isbn = isbn;
this.isAvailable = true;
}
borrow() {
if (this.isAvailable) {
this.isAvailable = false;
return `${this.title} has been borrowed.`;
} else {
return `${this.title} is not available.`;
}
}
return() {
this.isAvailable = true;
return `${this.title} has been returned.`;
}
getInfo() {
return `${this.title} by ${this.author} (${this.year}) - ISBN: ${this.isbn}`;
}
}
// 2. Create a Library class
class Library {
constructor(name) {
this.name = name;
this.books = [];
}
addBook(book) {
this.books.push(book);
return `${book.title} added to ${this.name}`;
}
removeBook(isbn) {
const index = this.books.findIndex(book => book.isbn === isbn);
if (index !== -1) {
const removedBook = this.books.splice(index, 1)[0];
return `${removedBook.title} removed from ${this.name}`;
}
return "Book not found";
}
findBook(isbn) {
return this.books.find(book => book.isbn === isbn);
}
listAvailableBooks() {
return this.books.filter(book => book.isAvailable);
}
getBookCount() {
return this.books.length;
}
}
// 3. Test the system
const library = new Library("My Library");
const book1 = new Book("JavaScript Guide", "John Doe", 2023, "123-456-789");
const book2 = new Book("React Basics", "Jane Smith", 2024, "987-654-321");
const book3 = new Book("Node.js Advanced", "Bob Wilson", 2023, "456-789-123");
library.addBook(book1);
library.addBook(book2);
library.addBook(book3);
console.log("Library:", library.name);
console.log("Total books:", library.getBookCount());
console.log(book1.borrow());
console.log(book2.borrow());
console.log(book1.return());
console.log("Available books:", library.listAvailableBooks().length);
// 4. Challenge: Add more features
// - Search books by title or author
// - Track borrowing history
// - Calculate overdue fees
// - Add categories/genres