JavaScript Objects: Basics, Access, Modification, and Nesting
What are JavaScript Objects?
- Objects in JavaScript are essentially key-value pairs, similar to dictionaries, maps, or hashmaps in other languages.
- Keys (also called properties) must be stored as strings.
- Values can be any datatype: booleans, strings, numbers, null, arrays, or even another object.
- Objects are used when you need to store complex data about an entity (e.g., a person or an employee) instead of many separate variables.
- Objects are created using curly braces: {}.
- Key ideas: each key is unique within an object; values can be of any datatype; properties describe the intent of the data.
Learning Objectives (quick recap)
- Understand what a JavaScript Object is
- Understand the advantages of objects
- Be able to create an object
- Be able to retrieve items from an object
- Be able to add items to an object
- Be able to modify an item in an object
Creating and Storing Objects
- Example of a plain data set (prior to using objects):
const firstName = "John";
const lastName = "Doe";
const jobTitle = "Project Manager";
const salary = 60000;
const currentProjects = ["FacebookForCats", "AmazonButBetter", "NotFlix", "Instant Gran"]; - Problem: adding more employees or data becomes unwieldy with separate variables.
- An object can model an employee with many properties in one structure:
const employee = {
firstName: "John",
lastName: "Doe",
jobTitle: "Project Manager",
salary: 60000,
currentProjects: ["FacebookForCats", "AmazonButBetter", "NotFlix", "Instant Gran"]
}
- Key points:
- Each property name (key) is descriptive and should reflect the datatype. Example: salary should represent a numeric value, not a string like "a lot".
- Property keys are strings (e.g., firstName, lastName).
- Properties can include any datatype, including arrays or nested objects.
- Practical naming tip: use descriptive property names to describe intent and datatype; avoid misleading names.
- Accessing data can be done with either bracket notation or dot notation.
Accessing Elements in Objects
- Bracket notation (works with a string key):
console.log(employee["firstName"]); - If a key does not exist, you get undefined:
console.log(employee["dateOfBirth"]); // undefined - Dot notation (more common when the key is a valid identifier):
console.log(employee.salary); - Important constraint: dot notation works only when the key is a plain identifier (no spaces, dots, dashes, or special characters). For keys with special characters, use bracket notation.
- Example of bracket notation for dateOfBirth:
// if dateOfBirth existed
console.log(employee["dateOfBirth"]);
Modifying Objects
- Check for the existence of a property:
console.log(employee.hasOwnProperty("firstName")); // true
console.log(employee.hasOwnProperty("height")); // false - Adding a new property (like adding a value to a variable):
employee.department = "engineering";
console.log(employee); - Replacing an existing value:
employee.firstName = "Jane";
console.log(employee); - Deleting a property using the delete operator (no brackets):
delete employee.salary;
console.log(employee); - Note: The delete operator removes the property from the object, not the object itself.
Listing and Exploring Object Data
- Objects have helpful methods to list keys or values (as arrays):
console.log(Object.keys(employee)); // ["firstName", "lastName", "jobTitle", "salary", "currentProjects", "department"]
console.log(Object.values(employee)); // ["Jane", "Doe", "Project Manager", undefined, […], "engineering"] - The transcript mentions employee.keys() and employee.arrays(), but the standard JavaScript methods are Object.keys() and Object.values(), optionally Object.entries() for key-value pairs.
- Be mindful of nesting: objects can contain other objects (nested objects), which adds complexity but models real-world data well.
Nested Objects and Accessing Nested Data
- Example with a nested address object inside employee:
const employee = {
firstName: "John",
lastName: "Doe",
jobTitle: "Project Manager",
salary: 60000,
currentProjects: ["FacebookForCats", "AmazonButBetter", "NotFlix", "Instant Gran"],
address: {
postCode: "EH6 4UH",
city: "Edinburgh",
street: "Newton Crescent",
number: 15
}
}
- The address property is itself an object.
- Accessing nested data:
- ToUpperCase example: console.log(employee.firstName.toUpperCase()); // "JOHN"
- To retrieve the city from the address object:
console.log(employee.address.city); // "Edinburgh"
- You can break out nested objects into separate variables for clarity:
const addressObject = employee.address;
console.log(addressObject.city); // "Edinburgh" - Key takeaway: chaining allows you to drill into nested structures, but you should keep track of data evolution to avoid confusion.
- Nested objects can be as deep as needed, but deep nesting can become hard to manage.
Practical Considerations and Best Practices
- Always use descriptive property names that clearly indicate the data type and meaning.
- If a property name would require special characters (spaces, dashes, dots), access it with bracket notation:
const value = obj["property-with-dashes"]; - When modeling real-world data, nesting is natural but should be kept to a reasonable depth to retain readability and maintainability.
- If you need to store a date, consider using a proper date type (e.g., a Date object) rather than an array or string that could be ambiguous; choose the representation that makes your intent clear.
- Access methods:
- Dot notation for simple, valid identifiers.
- Bracket notation for keys that are not valid identifiers or are computed dynamically.
Quick Reference Snippets
- Create an object:
const obj = {
key1: "value1",
key2: 42
}; - Access with dot notation:
obj.key1 - Access with bracket notation:
obj["key2"] - Check for key existence:
obj.hasOwnProperty("key1") - Add/modify properties:
obj.newKey = "newValue"; // add
obj.key1 = "newValue"; // modify - Delete a property:
delete obj.key2 - List keys/values:
Object.keys(obj)
Object.values(obj)
Object.entries(obj) - Nested object access:
obj.nested.key
Summary
- JavaScript objects are a core data structure for modeling complex data via key-value pairs.
- Keys are strings; values can be any type, including arrays and other objects.
- Objects are created with {} and accessed using dot notation or bracket notation.
- You can check for properties, set new properties, replace values, and delete properties.
- Objects can be nested, enabling rich data models, with chaining used to access deep values.
- Practical tips include using descriptive keys, preferring bracket notation for non-identifier keys, and using built-in utilities like Object.keys/Object.values for inspection.