Skip to content

Instantly share code, notes, and snippets.

@paulfryzel
Created September 22, 2025 21:18
Show Gist options
  • Select an option

  • Save paulfryzel/0b1ba36d19246febfd105f00c64cb792 to your computer and use it in GitHub Desktop.

Select an option

Save paulfryzel/0b1ba36d19246febfd105f00c64cb792 to your computer and use it in GitHub Desktop.
JavaScript Address Book Object
// JavaScript Address Book Object
// Creates objects to store people's address information
// Address constructor function
function Address(name, street, city, state, zipCode) {
this.name = name;
this.street = street;
this.city = city;
this.state = state;
this.zipCode = zipCode;
// Method to display address information
this.displayAddress = function() {
return `${this.name}\n${this.street}\n${this.city}, ${this.state} ${this.zipCode}`;
};
}
// Create address objects using the constructor
const addresses = [
new Address("John Smith", "123 Main St", "New York", "NY", "10001"),
new Address("Jane Doe", "456 Oak Ave", "Los Angeles", "CA", "90210"),
new Address("Bob Johnson", "789 Pine Rd", "Chicago", "IL", "60601")
];
// Alternative: Object literal approach
const addressBook = {
contacts: [
{
name: "Alice Brown",
street: "321 Elm St",
city: "Miami",
state: "FL",
zipCode: "33101"
},
{
name: "Charlie Wilson",
street: "654 Maple Dr",
city: "Seattle",
state: "WA",
zipCode: "98101"
}
],
// Method to add a new address
addAddress: function(name, street, city, state, zipCode) {
this.contacts.push({
name: name,
street: street,
city: city,
state: state,
zipCode: zipCode
});
},
// Method to find an address by name
findByName: function(name) {
return this.contacts.find(contact => contact.name === name);
},
// Method to display all addresses
displayAll: function() {
this.contacts.forEach(contact => {
console.log(`${contact.name}\n${contact.street}\n${contact.city}, ${contact.state} ${contact.zipCode}\n`);
});
}
};
// Example usage:
console.log("Using constructor function:");
addresses.forEach(addr => console.log(addr.displayAddress() + "\n"));
console.log("\nUsing object literal approach:");
addressBook.displayAll();
// Add a new address
addressBook.addAddress("David Lee", "987 Cedar Ln", "Austin", "TX", "78701");
console.log("\nAfter adding David Lee:");
console.log(addressBook.findByName("David Lee"));
// Export for use in other modules (if using Node.js)
if (typeof module !== 'undefined' && module.exports) {
module.exports = { Address, addressBook };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment