JavaScript Object Properties
JavaScript objects are collections of key-value pairs called properties. Understanding how to work with these properties is fundamental to mastering JavaScript. This guide will walk you through everything you need to know about object properties, from basic access to advanced concepts.
Introduction to Object Properties
In JavaScript, objects are dynamic collections of properties. Each property has a name (also called a key) and a value. The value can be any valid JavaScript data type, including numbers, strings, booleans, arrays, functions, or even other objects.
const person = {
firstName: "John", // String property
lastName: "Doe", // String property
age: 30, // Number property
isEmployed: true, // Boolean property
hobbies: ["reading", "coding", "hiking"], // Array property
address: { // Object property
street: "123 Main St",
city: "Boston",
country: "USA"
},
greet: function() { // Function property (method)
console.log("Hello!");
}
};
Accessing Object Properties
There are two main ways to access object properties: dot notation and bracket notation.
Dot Notation
Dot notation is the most straightforward way to access properties:
const person = {
firstName: "John",
lastName: "Doe"
};
// Accessing properties using dot notation
console.log(person.firstName); // Output: "John"
console.log(person.lastName); // Output: "Doe"
Bracket Notation
Bracket notation allows you to use strings and variables to access properties:
const person = {
firstName: "John",
lastName: "Doe"
};
// Accessing properties using bracket notation
console.log(person["firstName"]); // Output: "John"
// Using variables with bracket notation
const propertyName = "lastName";
console.log(person[propertyName]); // Output: "Doe"
When to Use Bracket Notation
Bracket notation is particularly useful in the following scenarios:
- When the property name contains special characters or spaces:
const specialObject = {
"special-property": "value",
"property with spaces": "another value"
};
console.log(specialObject["special-property"]); // Output: "value"
console.log(specialObject["property with spaces"]); // Output: "another value"
- When the property name is determined dynamically:
function accessProperty(obj, propName) {
return obj[propName]; // Dynamic property access
}
const user = {
name: "Alice",
email: "[email protected]"
};
console.log(accessProperty(user, "name")); // Output: "Alice"
console.log(accessProperty(user, "email")); // Output: "[email protected]"
Adding and Modifying Properties
JavaScript objects are mutable, allowing you to add and modify properties at any time.
Adding New Properties
You can add properties to an existing object using either dot notation or bracket notation:
const car = {
make: "Toyota",
model: "Corolla"
};
// Adding new properties
car.year = 2020;
car["color"] = "blue";
console.log(car);
// Output: { make: "Toyota", model: "Corolla", year: 2020, color: "blue" }
Modifying Existing Properties
Changing a property's value works the same way as adding a property:
const car = {
make: "Toyota",
model: "Corolla",
year: 2019
};
// Modifying properties
car.year = 2020;
car["model"] = "Camry";
console.log(car);
// Output: { make: "Toyota", model: "Camry", year: 2020 }
Deleting Properties
The delete
operator allows you to remove properties from an object:
const person = {
name: "Sarah",
age: 25,
occupation: "Developer"
};
// Deleting a property
delete person.occupation;
console.log(person); // Output: { name: "Sarah", age: 25 }
console.log(person.occupation); // Output: undefined
Property Existence Check
There are several ways to check if a property exists in an object:
Using the in
Operator
const car = {
make: "Honda",
model: "Civic",
year: 2018
};
console.log("make" in car); // Output: true
console.log("color" in car); // Output: false
Using hasOwnProperty()
The hasOwnProperty()
method is more specific as it only checks the object's own properties, not inherited ones:
const car = {
make: "Honda",
model: "Civic"
};
console.log(car.hasOwnProperty("make")); // Output: true
console.log(car.hasOwnProperty("toString")); // Output: false (inherited from Object.prototype)
Using Undefined Check
You can also check if a property exists by comparing it to undefined
, but this approach has limitations since a property might actually have the value undefined
:
const user = {
name: "John",
email: undefined
};
console.log(user.name !== undefined); // Output: true
console.log(user.email !== undefined); // Output: false (even though the property exists)
console.log(user.age !== undefined); // Output: false
Property Attributes and Descriptors
In JavaScript, properties have attributes that define their behavior. These attributes can be manipulated using property descriptors.
Basic Property Attributes
Each property has these attributes:
value
: The property's valuewritable
: Whether the property can be changedenumerable
: Whether the property appears infor...in
loops andObject.keys()
configurable
: Whether the property can be deleted or its attributes modified
Using Object.defineProperty()
You can define or modify a property with specific attributes:
const product = {};
// Define a property with custom attributes
Object.defineProperty(product, 'name', {
value: 'Laptop',
writable: true,
enumerable: true,
configurable: true
});
// Define a read-only property
Object.defineProperty(product, 'id', {
value: 'PRD123',
writable: false, // Cannot be changed
enumerable: true,
configurable: false // Cannot be deleted
});
product.name = "Desktop"; // This works
console.log(product.name); // Output: "Desktop"
product.id = "PRD456"; // This won't work (no error in non-strict mode)
console.log(product.id); // Output: "PRD123" (value remains unchanged)
Getting Property Descriptors
You can inspect a property's attributes using Object.getOwnPropertyDescriptor()
:
const product = {
name: "Phone"
};
Object.defineProperty(product, 'price', {
value: 599,
writable: false,
enumerable: true,
configurable: true
});
const nameDescriptor = Object.getOwnPropertyDescriptor(product, 'name');
console.log(nameDescriptor);
// Output: { value: "Phone", writable: true, enumerable: true, configurable: true }
const priceDescriptor = Object.getOwnPropertyDescriptor(product, 'price');
console.log(priceDescriptor);
// Output: { value: 599, writable: false, enumerable: true, configurable: true }
Computed Property Names
ES6 introduced computed property names, allowing you to use expressions as property names in object literals:
const propKey = "username";
const propValue = "johndoe";
// Using computed property name
const user = {
[propKey]: propValue,
[`${propKey}_verified`]: true
};
console.log(user);
// Output: { username: "johndoe", username_verified: true }
Property Shorthand
If a variable name and a property name are the same, you can use property shorthand:
const name = "John";
const age = 30;
// Using property shorthand
const person = { name, age };
console.log(person); // Output: { name: "John", age: 30 }
// Equivalent to:
const personLong = { name: name, age: age };
Method Definition Shorthand
ES6 also introduced a shorter syntax for defining methods:
// Old way
const calculator = {
add: function(a, b) {
return a + b;
}
};
// Method shorthand
const calculatorES6 = {
add(a, b) {
return a + b;
}
};
console.log(calculator.add(5, 3)); // Output: 8
console.log(calculatorES6.add(5, 3)); // Output: 8
Property Enumeration
JavaScript offers several ways to iterate through an object's properties.
for...in Loop
The for...in
loop iterates over all enumerable properties of an object:
const person = {
name: "Emma",
age: 28,
occupation: "Designer"
};
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
// Output:
// name: Emma
// age: 28
// occupation: Designer
Object.keys()
Returns an array of an object's own enumerable property names:
const person = {
name: "Emma",
age: 28,
occupation: "Designer"
};
const keys = Object.keys(person);
console.log(keys); // Output: ["name", "age", "occupation"]
keys.forEach(key => {
console.log(`${key}: ${person[key]}`);
});
Object.values()
Returns an array of an object's own enumerable property values:
const person = {
name: "Emma",
age: 28,
occupation: "Designer"
};
const values = Object.values(person);
console.log(values); // Output: ["Emma", 28, "Designer"]
Object.entries()
Returns an array of an object's own enumerable property [key, value] pairs:
const person = {
name: "Emma",
age: 28,
occupation: "Designer"
};
const entries = Object.entries(person);
console.log(entries);
// Output: [["name", "Emma"], ["age", 28], ["occupation", "Designer"]]
entries.forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
Real-world Example: Product Configuration
Let's see a practical example of using object properties to build a configurable product system:
function createProduct(name, basePrice, options = {}) {
const product = {
name,
basePrice,
// Default options
options: {
color: options.color || "white",
size: options.size || "medium",
warranty: options.warranty || "1 year"
},
// Computed property
get fullName() {
return `${this.options.color} ${this.name} (${this.options.size})`;
},
// Calculate final price based on options
calculatePrice() {
let finalPrice = this.basePrice;
// Add price for premium color
if (this.options.color === "black" || this.options.color === "silver") {
finalPrice += 50;
}
// Add price for size upgrade
if (this.options.size === "large") {
finalPrice += 100;
}
// Add price for extended warranty
if (this.options.warranty === "2 years") {
finalPrice += 75;
} else if (this.options.warranty === "3 years") {
finalPrice += 120;
}
return finalPrice;
},
// Display product information
displayInfo() {
return {
product: this.fullName,
price: `$${this.calculatePrice()}`,
warranty: this.options.warranty
};
}
};
return product;
}
// Create a basic laptop
const basicLaptop = createProduct("Laptop", 999);
console.log(basicLaptop.displayInfo());
// Output: { product: "white Laptop (medium)", price: "$999", warranty: "1 year" }
// Create a premium laptop with custom options
const premiumLaptop = createProduct("Laptop Pro", 1499, {
color: "silver",
size: "large",
warranty: "3 years"
});
console.log(premiumLaptop.displayInfo());
// Output: { product: "silver Laptop Pro (large)", price: "$1769", warranty: "3 years" }
Summary
JavaScript object properties are a fundamental concept for working with data in JavaScript. We've explored:
- How to access properties using dot and bracket notation
- Adding, modifying, and deleting properties
- Checking for property existence
- Property descriptors and their attributes
- Modern JavaScript features like computed property names and shorthands
- Methods for enumerating object properties
- Practical applications in real-world scenarios
Understanding object properties is essential for effective JavaScript programming, as objects are used extensively in the language for everything from simple data storage to complex applications.
Additional Resources
- MDN Web Docs: Working with Objects
- MDN Web Docs: Object.defineProperty()
- JavaScript.info: Object properties configuration
Exercises
-
Create an object representing a book with properties for title, author, and year. Then add a method that returns the book's age (current year - publication year).
-
Write a function that takes an object and a string path (like "user.address.city") and returns the value at that path, or undefined if the path doesn't exist.
-
Create an object with a private property (using property descriptors) that can only be accessed and modified through getter and setter methods.
-
Implement a function that merges two objects, where properties from the second object overwrite properties from the first if they have the same key.
-
Create an object representing a shopping cart that allows adding items, removing items, and calculating the total price.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)