Properties list in JavaScript
JavaScript Fundamentals
Create, Access, and Iterate JavaScript Object Properties
Object literals are the backbone of JavaScript applications. They store configuration, API responses, and UI state in an easy-to-read format. This guide walks through building a nested object, accessing values, and iterating properties safely.
Object Literals
Define key–value data inline using curly braces. Ideal for configuration and mock data.
Property Access
Use dot notation for known keys, bracket notation for dynamic keys.
Iteration Patterns
Loop through objects with for...in, Object.keys(), or Object.entries().
1. Define a Nested Object
Start with a single literal that groups fruit nutrition facts. Each fruit is another object containing macronutrient values.
const fruits = {
apple: {
water: "86%",
protein: "0.3 g",
fat: "0.2 g",
sugars: "10.4 g"
},
mango: {
water: "83.5 g",
protein: "0.8 g",
fat: "0.4 g",
sugars: "14.8 g"
}
};
Tip: Keep numeric units in strings if they include symbols (%, g). Otherwise, store numbers and add units when rendering.
2. Access Properties
Dot Notation
const appleProtein = fruits.apple.protein;
console.log(appleProtein); // "0.3 g"
Bracket Notation
const fruitName = "mango";
const nutrient = "sugars";
console.log(fruits[fruitName][nutrient]); // "14.8 g"
3. Iterate Over Properties
Choose an iteration strategy based on the data you need. The examples below log each nutrient for every fruit.
for...in Loop
for (const property in fruits.apple) {
if (Object.prototype.hasOwnProperty.call(fruits.apple, property)) {
console.log(`${property}: ${fruits.apple[property]}`);
}
}
Object.entries()
Object.entries(fruits).forEach(([fruitName, stats]) => {
console.log(`\n${fruitName.toUpperCase()}`);
Object.entries(stats).forEach(([nutrient, value]) => {
console.log(`- ${nutrient}: ${value}`);
});
});
4. Present Objects as Tables
When displaying object data in the browser, render it in a table to improve readability.
| Fruit | Water | Protein | Fat | Sugars |
|---|---|---|---|---|
| Apple | 86% | 0.3 g | 0.2 g | 10.4 g |
| Mango | 83.5 g | 0.8 g | 0.4 g | 14.8 g |
Best Practices
Recommended
- Freeze configuration objects with
Object.freeze(). - Namespace related data in nested objects for clarity.
- Use TypeScript or JSDoc to document expected properties.
Avoid
- Mutating objects in multiple places without tracking state.
- Using
for...inwithouthasOwnProperty. - Mixing numeric and string keys unless absolutely necessary.