Establishing Consistency in Object Property Definitions
Create standards for defining and accessing object properties to enhance clarity and reduce bugs in your JavaScript code.
0 likes
193 views
Rule Content
---
title: Establishing Consistency in Object Property Definitions
description: Create standards for defining and accessing object properties to enhance clarity and reduce bugs in your JavaScript code.
category: JavaScript Cursor Rules
---
# Rule: Consistent Object Property Definitions
## Objective
Ensure uniformity in defining and accessing object properties to improve code readability, maintainability, and reduce potential errors in JavaScript projects.
## Guidelines
1. **Use Consistent Naming Conventions:**
- Employ `camelCase` for property names (e.g., `userName`, `orderTotal`).
- Avoid using reserved words or special characters in property names.
2. **Define Object Properties Explicitly:**
- Initialize all object properties at the time of object creation to prevent `undefined` values.
- Use default values where applicable to ensure properties have meaningful initial states.
3. **Access Object Properties Safely:**
- Utilize optional chaining (`?.`) when accessing nested properties to prevent runtime errors.
- Use nullish coalescing (`??`) to provide default values when properties are `null` or `undefined`.
4. **Avoid Using `Object` as a Property Type:**
- Specify more precise types for object properties to enhance type safety and code clarity.
5. **Prevent Property Modification:**
- Use `Object.freeze()` to create immutable objects when properties should not be modified after creation.
## Examples
**Consistent Naming Conventions:**
// Good
const user = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
// Bad
const user = {
First_Name: 'John',
last_name: 'Doe',
Age: 30
};
**Explicit Property Definitions:**
// Good
const order = {
id: 123,
total: 0.0,
items: []
};
// Bad
const order = {
id: 123
};
**Safe Property Access:**
// Good
const userCity = user.address?.city ?? 'Unknown';
// Bad
const userCity = user.address.city;
**Avoid Using `Object` as a Property Type:**
// Good
/**
* @typedef {Object} User
* @property {string} firstName
* @property {string} lastName
* @property {number} age
*/
/** @type {User} */
const user = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
// Bad
/** @type {Object} */
const user = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
**Prevent Property Modification:**
// Good
const config = Object.freeze({
apiUrl: 'https://api.example.com',
timeout: 5000
});
// Bad
const config = {
apiUrl: 'https://api.example.com',
timeout: 5000
};
## References
- ECMAScript® 2025 Language Specification: [Object.defineProperty](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.defineproperty)
- ECMAScript® 2025 Language Specification: [Object.freeze](https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.freeze)