Find Object Property
Access and return a specific property from an object.
Object property access is fundamental to JavaScript programming. This exercise teaches you the different ways to access object values and when each method is appropriate.
π Concepts & Theory
Accessing object properties is fundamental in JavaScript. Objects are key-value pairs that store data, and JavaScript provides multiple syntaxes for property access.
Understanding Object Property Access:
Method 1: Dot Notation (Most Common)
const person = { name: "Alice", age: 30 };
console.log(person.name); // "Alice"
Method 2: Bracket Notation (Dynamic Access)
const key = "name";
console.log(person[key]); // "Alice"
Method 3: Destructuring (ES6+)
const { name, age } = person;
console.log(name); // "Alice"
When to Use Each:
Dot Notation:
- Property name is known at write-time
- Property name is a valid identifier (no spaces/special chars)
- Most readable and common
- Property name is in a variable
- Property name has spaces or special characters
- Property name is a number
- Dynamic property access
const obj = {
"first name": "Alice", // Space in property name
age: 30,
1: "one" // Numeric key
};
obj.age; // β
Works
obj["first name"]; // β
Only way to access
obj.1; // β Syntax error
obj[1]; // β
Works
const prop = "age";
obj.prop; // β undefined (looks for property named "prop")
obj[prop]; // β
"30" (evaluates variable)
Optional Chaining (ES2020):
const name = person?.name; // Safe access, returns undefined if person is null
Object Property Checking:
"name" in person; // true
person.hasOwnProperty("name"); // true π― Your Challenge
Write getProperty that returns the value of a property.
π Starter Code
function getProperty(obj, key) {
// Your code here
}
console.log(getProperty({name: 'John', age: 30}, 'name'));
- You need to access a property whose name is in a variable
- Dot notation won't work here because the key is dynamic
- Use square brackets [] for dynamic property access
- The syntax is object[propertyName]
- Return the value directly using obj[key]
Solution
function getProperty(obj, key) {
return obj[key];
}
console.log(getProperty({name: 'John', age: 30}, 'name'));
Explanation
This solution uses bracket notation to access the object property. The function takes an object and a key (property name) as parameters, then returns obj[key]. Bracket notation is essential here because the property name is dynamicβstored in a variable rather than hardcoded. Attempting obj.key would look for a property literally named "key" rather than the value of the key parameter. This demonstrates why bracket notation is crucial for dynamic property access. Time complexity: O(1). Space complexity: O(1).
β οΈ Common Mistakes to Avoid
- Using dot notation with a variable (obj.key instead of obj[key])
- Forgetting quotes around property names with spaces
- Not checking if property exists before accessing
- Confusing obj.key and obj['key']
- Trying to use dot notation with numeric keys