### Async Get User Example
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Example of an asynchronous function to fetch user data.
```js
async function getUser(id) {
const user = await fetch(`/api/user/${id}`)
return user
}
```
--------------------------------
### Reset Fruits Example
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Example of a function to reset the fruits variable to its initial value.
```js
const initialFruits = 5
let fruits = initialFruits
setFruits(10)
console.log(fruits) // 10
function resetFruits() {
fruits = initialFruits
}
resetFruits()
console.log(fruits) // 5
```
--------------------------------
### Set Fruits Example
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Example of a function to set a new value for the fruits variable. Demonstrates declarative assignment.
```js
let fruits = 0
function setFruits(nextFruits) {
fruits = nextFruits
}
setFruits(5)
console.log(fruits) // 5
```
--------------------------------
### Get Fruit Count Example
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Example of a simple getter function to retrieve the count of fruits.
```js
function getFruitCount() {
return this.fruits.length
}
```
--------------------------------
### Compose Page URL Example
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Example of a function that creates a new page URL string by combining page name and ID.
```js
function composePageUrl(pageName, pageId) {
return pageName.toLowerCase() + '-' + pageId
}
```
--------------------------------
### Decision Tree for get vs. fetch
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use 'get' for immediately available data (synchronous or cached) and 'fetch' for data from a remote source.
```text
Is the data immediately available?
├─ Yes (synchronous/cached) → use "get" (getUser)
└─ No → Is it from a remote source?
├─ Yes (API call) → use "fetch" (fetchPosts)
└─ No (local async) → use "get" (getUser) or "fetch"
```
--------------------------------
### Correct Example: Using Natural Prefixes
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Employ natural English prefixes like 'has' to indicate presence, as in 'hasPagination'. This makes the intent clear and efficient, aligning with the S.I.D principles.
```javascript
const hasPagination = postCount > 10
// ✓ Uses natural English prefix "has"
// ✓ Clear intent: indicates presence of pagination feature
// ✓ Efficient: single identifier communicates the complete concept
```
--------------------------------
### Action Verbs for Naming
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/README.md
Use these action verbs to describe the primary operation of a function. Examples show common use cases.
```text
| Action | Use Case | Example |
|---|---|---|
| `get` | Retrieve data (sync or async) | `getUser()`, `getMessages()` |
| `set` | Assign value | `setCount()`, `setName()` |
| `reset` | Restore initial state | `resetForm()`, `resetCounter()` |
| `remove` | Extract from collection | `removeItem()`, `removeFilter()` |
| `delete` | Permanently erase | `deleteUser()`, `deletePost()` |
| `compose` | Create by combining | `composeUrl()`, `composeConfig()` |
| `handle` | Respond to event | `handleClick()`, `handleError()` |
```
--------------------------------
### Correct Example: Using Natural Verbs
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Utilize natural English verbs like 'paginate' with appropriate prefixes such as 'should' to convey intent, as in 'shouldPaginate'. This ensures clarity and adherence to S.I.D principles.
```javascript
const shouldPaginate = postCount > 10
// ✓ Natural English word "paginate"
// ✓ Clear intent with "should" prefix
// ✓ Alternatives: all acceptable with S.I.D balance
```
--------------------------------
### Handle Error Example
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use to indicate that the caller should handle the error. The function name follows the 'should' prefix, 'handle' action, and 'Error' high context.
```javascript
// "You should handle the error"
shouldHandleError(error)
```
--------------------------------
### Common Use Cases for Handle Functions
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Examples of `handle` functions used for event listeners, error callbacks, and lifecycle callbacks in various programming contexts.
```javascript
// Event handlers
form.addEventListener('submit', handleFormSubmit)
button.addEventListener('click', handleButtonClick)
input.addEventListener('change', handleInputChange)
// Error callbacks
promise.catch(handleError)
request.onError(handleRequestError)
// Lifecycle callbacks
React.useEffect(() => handleComponentMount(), [])
window.addEventListener('load', handlePageLoad)
```
--------------------------------
### Asynchronous Get Function
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use `get` for asynchronous data fetching. The `await` keyword and context reveal that the function is async.
```javascript
async function getUser(id) {
const response = await fetch(`/api/users/${id}`)
return response.json()
}
const user = await getUser(123)
```
--------------------------------
### Get Multiple Users Functions
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Use plural names for functions that return a collection of items. This includes direct database queries or filtered results.
```javascript
function getAllUsers() {
return database.find({}) // Returns user collection
}
```
```javascript
function getActiveUsers(users) {
return users.filter(u => u.isActive) // Returns filtered collection
}
```
```javascript
function getUserFriends(userId) {
return database.find({ friendOfId: userId }) // Returns collection
}
```
--------------------------------
### Short, Intuitive, and Descriptive Naming (S-I-D)
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Names should be short, intuitive, and descriptive. Avoid ambiguous names, unnatural terms, and made-up verbs. This example illustrates the S-I-D principle.
```javascript
/* Bad */
const a = 5 // "a" could mean anything
const isPaginatable = a > 10 // "Paginatable" sounds extremely unnatural
const shouldPaginatize = a > 10 // Made up verbs are so much fun!
/* Good */
const postCount = 5
const hasPagination = postCount > 10
const shouldPaginate = postCount > 10 // alternatively
```
--------------------------------
### Remove Filter Example
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Example of a function to remove a specific filter from a collection of selected filters.
```js
function removeFilter(filterName, filters) {
return filters.filter((name) => name !== filterName)
}
const selectedFilters = ['price', 'availability', 'size']
removeFilter('price', selectedFilters)
```
--------------------------------
### Validate Form Example
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use to indicate that the caller should validate the form. The function name follows the 'should' prefix, 'validate' action, and 'Form' high context.
```javascript
// "You should validate the form"
shouldValidateForm(form)
```
--------------------------------
### Synchronous Get Function
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use `get` for synchronous retrieval of internal data. The function name does not indicate if it's async.
```javascript
function getFruitCount() {
return this.fruits.length
}
const count = getFruitCount()
```
--------------------------------
### Consistent Naming Conventions
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Choose and consistently apply a single naming convention (e.g., camelCase, PascalCase, snake_case). This snippet demonstrates good and bad examples of naming convention consistency.
```javascript
/* Bad */
const page_count = 5
const shouldUpdate = true
/* Good */
const pageCount = 5
const shouldUpdate = true
/* Good as well */
const page_count = 5
const should_update = true
```
--------------------------------
### Get Single User Functions
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Use singular names for functions that return a single value or undefined. This applies whether fetching from a database or processing a collection.
```javascript
function getFirstUser(users) {
return users[0] // Returns single user or undefined
}
```
```javascript
function getUserById(id) {
return database.find({ id }).first() // Returns one user
}
```
--------------------------------
### Form Self-Validation Example
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use to indicate that the form should validate itself. The function name follows the 'should' prefix, 'Form' high context, and 'Validate' action.
```javascript
// "The form should validate itself"
shouldFormValidate(form)
```
--------------------------------
### Compose Function to Create From Components
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use `compose` to create new data by combining or transforming existing data. This is distinct from `get` as it creates new data rather than retrieving existing.
```javascript
function composePageUrl(pageName, pageId) {
return pageName.toLowerCase() + '-' + pageId
}
const url = composePageUrl('About', 42)
```
--------------------------------
### Correct Example: Descriptive Variable Name
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Use descriptive names like 'postCount' that clearly indicate the variable's purpose. This name is short, intuitive, and descriptive, adhering to the S.I.D principles.
```javascript
const postCount = 5
// ✓ Short: 9 characters
// ✓ Intuitive: clearly refers to count of posts
// ✓ Descriptive: specificity of "post" + "count" conveys purpose
```
--------------------------------
### Reflect Expected Result in Names
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
A name should accurately reflect the expected outcome or state. This example demonstrates how to name a variable to clearly indicate its purpose in a conditional rendering scenario.
```jsx
/* Bad */
const isEnabled = itemCount > 3
return
/* Good */
const isDisabled = itemCount <= 3
return
```
--------------------------------
### Avoid Contractions in Names
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Do not use contractions in names to maintain code readability. This example shows the difference between using a contraction and a full word.
```javascript
/* Bad */
const onItmClk = () => {}
/* Good */
const onItemClick = () => {}
```
--------------------------------
### Error Handler Self-Handling Example
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use to indicate that the error handler should handle the error. The function name follows the 'should' prefix, 'errorHandler' high context, and 'handle' action.
```javascript
// "The error handler should handle this error"
shouldErrorHandlerHandle(error)
```
--------------------------------
### Function Operating on Posts
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Shows a function specifically designed to get recent posts, utilizing a general filter function. Assumes a 'post' object structure with a 'date' property.
```javascript
/* Function operating exactly on posts */
function getRecentPosts(posts) {
return filter(posts, (post) => post.date === Date.now())
}
```
--------------------------------
### Avoid Context Duplication in Names
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Do not duplicate the context within a name if it doesn't decrease readability. Remove the context from the name when possible. This example shows a class method name avoiding context duplication.
```javascript
class MenuItem {
/* Method name duplicates the context (which is "MenuItem") */
handleMenuItemClick = (event) => { ... }
/* Reads nicely as `MenuItem.handleClick()` */
handleClick = (event) => { ... }
}
```
--------------------------------
### Boolean Characteristic and State Check
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Illustrates how to use 'is' prefix for checking characteristics (e.g., color) and states (e.g., presence). Useful for conditional logic.
```javascript
const color = 'blue'
const isBlue = color === 'blue' // characteristic
const isPresent = true // state
if (isBlue && isPresent) {
console.log('Blue is present!')
}
```
--------------------------------
### Generated Documentation Structure
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/MANIFEST.md
This snippet shows the directory structure of the generated documentation files. It includes the main README, topic-specific documents, and the manifest file itself.
```text
output/
├── README.md (main index and navigation)
├── 01-project-overview.md (scope)
├── 02-core-principles.md (S.I.D, conventions, context)
├── 03-function-naming-pattern.md (A/HC/LC, verbs, prefixes)
├── 04-cardinality-conventions.md (singular/plural rules)
├── 05-naming-glossary.md (quick reference, decision trees)
└── MANIFEST.md (this file)
```
--------------------------------
### Configuration Objects: Singular vs. Plural Collections
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Use singular names for a single configuration object and plural names for collections of configurations.
```javascript
// Configuration is singular (one config object)
const config = loadConfiguration()
const settings = getUserSettings()
```
```javascript
// But collection of configs is plural
const environmentConfigs = loadAllConfigs()
const userSettings = getAllUserSettings()
```
--------------------------------
### State Transitions with 'prev' and 'next'
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use 'prev' and 'next' prefixes to indicate the previous or next state of a variable, useful for tracking state transitions, changes, or iterations.
```javascript
async function getPosts() {
const prevPosts = this.state.posts // Current state
const latestPosts = await fetch('/api/posts')
const nextPosts = [...prevPosts, ...latestPosts] // New state
this.setState({ posts: nextPosts })
}
```
```javascript
function iterate(items) {
let prevItem = null
for (let nextItem of items) {
if (prevItem) {
processTransition(prevItem, nextItem)
}
prevItem = nextItem
}
}
```
```javascript
const prevState = { count: 0 }
const nextState = { count: 1 }
dispatch(prevState, nextState)
```
```javascript
async function updateData() {
const prevData = cache.get('data')
const nextData = await fetchFreshData()
if (prevData !== nextData) {
notifySubscribers(prevData, nextData)
}
cache.set('data', nextData)
}
```
--------------------------------
### API/Data Fetching: Retrieval Patterns
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use sync getters for direct retrieval, async fetches for network requests, and search/find operations for specific data lookups.
```javascript
// Retrieval patterns
const user = getUser(id) // Sync getter
const users = await fetchUsers() // Async fetch
const user = await findUser(id) // Search operation
const users = await searchUsers(query) // Query operation
```
--------------------------------
### Paired Operations: Add/Remove and Create/Delete
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Illustrates the semantic pairing of operations: `add` with `remove` for collections, and `create` with `delete` for permanent entity management.
```javascript
// Good: paired operations make sense
users.add(newUser) // Add to users collection
users.remove(userId) // Remove from users collection
user = createUser(data) // Create new user entity
deleteUser(userId) // Permanently delete the user
```
--------------------------------
### State Management: Transition Naming
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Name previous and next states clearly to track changes. Use spread syntax for immutably updating state objects.
```javascript
// Transition naming
const prevState = state
const nextState = { ...state, count: count + 1 }
```
--------------------------------
### Handle Function for Responding to Events
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use `handle` for naming callback methods and event handlers. The pattern is `handle` + event/action + optional context.
```javascript
function handleLinkClick() {
console.log('Clicked a link!')
}
link.addEventListener('click', handleLinkClick)
```
--------------------------------
### Boundary Values with 'min' and 'max'
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Utilize 'min' and 'max' prefixes to denote minimum or maximum values, commonly used for boundaries, limits, or range constraints.
```javascript
/**
* Renders a random number of posts within the given boundaries.
*/
function renderPosts(posts, minPosts, maxPosts) {
const count = randomBetween(minPosts, maxPosts)
return posts.slice(0, count)
}
renderPosts(allPosts, 5, 10) // Render between 5-10 posts
```
```javascript
function fetchPosts(minId, maxId, minDate, maxDate) {
// Fetch posts between min and max boundaries
return db.query({
id: { $gte: minId, $lte: maxId },
date: { $gte: minDate, $lte: maxDate }
})
}
```
```javascript
const minPrice = 0
const maxPrice = 1000
const minRetries = 3
const maxRetries = 5
```
--------------------------------
### Use Acceptable Standard Abbreviations
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Illustrates the use of widely accepted standard abbreviations and common initialisms in variable names, which are considered acceptable due to industry-wide recognition.
```javascript
// Acceptable
const userId = 123
const apiKey = 'secret'
const isValidUrl = true
const xmlParser = new Parser()
```
--------------------------------
### State Management: Conditional Logic
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use logical operators with descriptive names to determine conditions for actions like refetching or pausing.
```javascript
// Conditional logic
const shouldRefetch = cacheExpired && hasInternet
const shouldPause = isPaused || isBuffering
```
--------------------------------
### Event Handling: Event-Specific Handlers
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
For specific browser or application events, use 'on' followed by the event name for clarity.
```javascript
// Event-specific handlers
const onWindowResize = () => { }
const onDocumentReady = () => { }
const onRouteChange = (route) => { }
```
--------------------------------
### Previous/Next State Indication
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Demonstrates the 'prev' and 'next' prefixes to indicate the previous or next state of a variable within the current context. Useful for tracking state transitions.
```javascript
async function getPosts() {
const prevPosts = this.state.posts
const latestPosts = await fetch('...')
const nextPosts = concat(prevPosts, latestPosts)
this.setState({ posts: nextPosts })
}
```
--------------------------------
### Context/Scope Patterns: Within Module Namespace
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
When exporting functions from a module, use concise names. The module itself provides the namespace, preventing ambiguity.
```javascript
// Within module namespace
// users module
export function getAll() { } // ✓ users.getAll()
export function findById() { } // ✓ users.findById()
```
--------------------------------
### Collection Naming: Grouped/Categorized
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use 'by' followed by the grouping key for objects that map items to categories.
```javascript
// Grouped/Categorized
const usersByRole = {}
const postsByAuthor = {}
const itemsByCategory = {}
```
--------------------------------
### API/Data Fetching: Modification Patterns
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Employ clear naming for creating, updating, deleting, and removing data entities. Use async operations for modifications that involve external systems.
```javascript
// Modification patterns
const user = await createUser(data)
const user = await updateUser(id, changes)
const success = await deleteUser(id)
const removed = removeUser(userId, userList)
```
--------------------------------
### Event Handling: Handler Naming
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Prefix event handler functions with 'on' followed by the event or element name. For generic handlers, use 'on' followed by the action.
```javascript
// Handler naming
const onButtonClick = () => { }
const onFormSubmit = (event) => { }
const onInputChange = (value) => { }
const onMouseEnter = (event) => { }
```
--------------------------------
### Boolean Conditional Action with 'should'
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use the 'should' prefix for variables that represent a positive conditional statement tied to an action, returning a boolean to control execution.
```javascript
function shouldUpdateUrl(url, expectedUrl) {
return url !== expectedUrl
}
if (shouldUpdateUrl(current, expected)) {
updateUrl(expected)
}
```
```javascript
const shouldRender = isVisible && !isHidden
const shouldFetch = cacheExpired && hasInternet
const shouldRetry = retryCount < maxRetries && lastError
const shouldNavigate = hasPermission && isValidRoute
```
```javascript
// Using `is` for characteristics
const isAdmin = user.role === 'admin' // ✓ "Is this user an admin?"
// Using `has` for possession
const hasAdminRole = user.roles.includes('admin') // ✓ "Does this have admin role?"
```
```javascript
// "Should I (caller) update the URL?"
shouldUpdateUrl(url, expected)
// "Should the URL update itself?" (within a URL handler)
shouldUrlUpdate(newUrl, oldUrl)
```
--------------------------------
### Reset Function to Restore Initial State
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use `reset` to revert a variable or state back to its initial or default value. The pattern is `reset` + context.
```javascript
const initialFruits = 5
let fruits = initialFruits
setFruits(10)
console.log(fruits)
function resetFruits() {
fruits = initialFruits
}
resetFruits()
console.log(fruits)
```
--------------------------------
### Decision Tree for Boolean Prefixes
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use 'is' for characteristics/states, 'has' for possession, 'should' for action conditions, and 'can' for capabilities. Fallback to 'is' or context-specific prefixes.
```text
Is it describing a characteristic or state?
├─ Yes → use "is" (isActive, isVisible)
└─ No → Does it describe possession?
├─ Yes → use "has" (hasChildren)
└─ No → Does it describe an action condition?
├─ Yes → use "should" (shouldRender)
└─ No → Does it describe capability?
├─ Yes → use "can" (canEdit)
└─ Otherwise → use "is" or context-specific prefix
```
--------------------------------
### Rust/Go Naming Conventions
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Highlights naming conventions in Rust/Go: snake_case for functions and module names, PascalCase for types/structs, and CONSTANT_CASE for constants.
```rust
// Functions: snake_case
fn get_user_posts(user_id: u32) { }
// Types/Structs: PascalCase
struct UserService { }
// Constants: CONSTANT_CASE
const MAX_RETRIES: u32 = 3;
// Module names: snake_case
mod user_service { }
```
--------------------------------
### Event Listeners and Callbacks: Singular vs. Plural
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Employ singular names for single event handlers and plural names when dealing with collections of handlers.
```javascript
// Single event handler (singular)
const onItemClick = (item) => { ... }
const handleSubmit = (event) => { ... }
```
```javascript
// Multiple handlers (plural)
const onItemClickHandlers = [handler1, handler2, handler3]
const formSubmitHandlers = getFormHandlers()
```
--------------------------------
### Event Handling: Handler Registration
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use 'handle' prefix for functions that process events, especially when they are registered as callbacks.
```javascript
// Handler registration
const handleClick = () => { }
const handleError = (error) => { }
const handleSuccess = (data) => { }
```
--------------------------------
### Database Query Results: Single vs. Multiple
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Use singular names for single database results and plural names for multiple results, even if the collection is empty or contains only one item.
```javascript
// Single result
const user = getUserById(123)
```
```javascript
// Multiple results (always plural, even if empty or one item)
const users = getUsers({ status: 'active' })
const posts = searchPosts('javascript')
const results = query(sql)
```
--------------------------------
### State Management: Current State Naming
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use descriptive boolean flags for loading and error states, and clear names for current user or data.
```javascript
// Current state naming
const isLoading = true
const hasError = false
const currentUser = user
```
--------------------------------
### A/HC/LC Function Naming Pattern
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/README.md
Follow the Action-High Context-Low Context pattern for function naming. Prefixes can be optionally included.
```text
[prefix?] + Action (A) + High Context (HC) + Low Context? (LC)
```
```text
getUser → get + User
```
```text
getUserMessages → get + User + Messages
```
```text
handleClickOutside → handle + Click + Outside
```
```text
shouldDisplayMessage → should + Display + Message
```
```text
isValidEmail → is + ValidEmail (prefix + combined context)
```
--------------------------------
### Pure Function with Primitives
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Demonstrates a pure function that filters a list based on a predicate. This is a general-purpose function.
```javascript
/* A pure function operating with primitives */
function filter(list, predicate) {
return list.filter(predicate)
}
```
--------------------------------
### JavaScript/TypeScript Naming Conventions
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Demonstrates common naming conventions: camelCase for variables and functions, PascalCase for classes, CONSTANT_CASE or camelCase for constants, and leading underscore or # for private members.
```javascript
// Variables and functions: camelCase
const userName = 'Alice'
function getUserPosts(id) { }
// Classes and constructors: PascalCase
class UserService { }
const userService = new UserService()
// Constants: CONSTANT_CASE or camelCase
const MAX_RETRIES = 3
const defaultConfig = { }
// Private members: leading underscore or # (modern)
class User {
_privateField = 'private'
#privateField = 'private' // TC39 private fields
}
```
--------------------------------
### Singular Naming for Object Properties and Instances
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
When defining properties of a class or creating instances, use singular names for individual properties and for variables holding a single object instance or result.
```javascript
class User {
name = 'John' // Single string value
email = 'john@example.com'
age = 30
isAdmin = false
createdDate = new Date()
}
const user = new User() // Single instance
const post = fetchPost(123) // Single entity
const result = processData() // Single result
```
--------------------------------
### Use Full Words for Variable Names
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Shows the correct pattern for naming variables by spelling out words completely, enhancing clarity and avoiding ambiguity.
```javascript
const onItemClick = () => { }
const getFriendList = () => { }
const isAvailable = true
const userPreferences = { }
```
--------------------------------
### Java/C# Naming Conventions
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Shows typical naming conventions in Java/C#: camelCase for variables and functions, PascalCase for classes, CONSTANT_CASE for constants, and conventions for private members.
```java
// Variables and functions: camelCase
String userName = "Alice";
void getUserPosts(int userId) { }
// Classes: PascalCase
class UserService { }
// Constants: CONSTANT_CASE
int MAX_RETRIES = 3;
// Private members
class User {
private String _field;
private String field; // Convention varies
}
```
--------------------------------
### Cardinality in Naming
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/README.md
Use singular nouns for single values and plural nouns for multiple values to indicate cardinality.
```text
| Count | Naming | Example |
|---|---|---|
| Single value | Singular | `user`, `post`, `count` |
| Multiple values | Plural | `users`, `posts`, `items` |
```
--------------------------------
### Decision Tree for remove vs. delete
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use 'delete' for permanent erasure and 'remove' for removal from a collection.
```text
Does the action permanently erase?
├─ Yes → use "delete" (deleteUser, deletePost)
└─ No → Does it remove from a collection?
├─ Yes → use "remove" (removeItem, removeFilter)
└─ No → depends on context
```
--------------------------------
### Inconsistent Naming Convention
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Avoid mixing different naming conventions within the same project, as it leads to confusion and reduces code readability.
```javascript
/* Bad — mixing conventions */
const page_count = 5 // snake_case
const shouldUpdate = true // camelCase
const MaxRetries = 3 // PascalCase
const finalResult = true // camelCase
```
--------------------------------
### Conditional Statement Prefix
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Shows the 'should' prefix for boolean variables that represent a positive conditional statement, often preceding an action. Useful for state management.
```javascript
function shouldUpdateUrl(url, expectedUrl) {
return url !== expectedUrl
}
```
--------------------------------
### Boolean Naming: can + verb
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use 'can' prefix for boolean variables that indicate permission or capability to perform an action.
```javascript
// can + verb
const canEdit = true
const canDelete = false
const canSubmit = true
```
--------------------------------
### Context order 1: Agent as high context
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use when the caller is responsible for invoking component updates. The interpretation is 'You (the caller) should update the component'.
```javascript
// Context order 1: Agent as high context
shouldUpdateComponent(component)
// Interpretation: "You (the caller) should update the component"
// The caller is responsible for invoking component updates
// Example use: if (shouldUpdateComponent(comp)) { comp.update() }
```
--------------------------------
### Context/Scope Patterns: Avoiding Redundancy
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Avoid repeating context in function names if the context is already clear from the class or module name. Prefer shorter, more specific names.
```javascript
// Avoiding redundancy
class UserService {
// ✗ Redundant: "User" is already in class name
getUserData(id) { }
// ✓ Better: context implied
getData(id) { }
// ✗ Redundant
getAllUsers() { }
// ✓ Better
getAll() { }
}
```
--------------------------------
### Boolean Naming: should + verb
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use 'should' prefix for boolean variables that indicate a condition for performing an action or a future state.
```javascript
// should + verb
const shouldRender = true
const shouldPaginate = false
const shouldRetry = true
```
--------------------------------
### Collection Naming: Simple Collections
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use plural nouns for arrays or lists that hold multiple items of the same type.
```javascript
// Simple collections
const users = []
const posts = []
const tags = []
```
--------------------------------
### Boolean Check for Possession
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Demonstrates the 'has' prefix for checking if a context possesses a certain value or state, contrasting it with less clear alternatives. Preferred for readability.
```javascript
/* Bad */
const isProductsExist = productsCount > 0
const areProductsPresent = productsCount > 0
/* Good */
const hasProducts = productsCount > 0
```
--------------------------------
### Python Naming Conventions
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Illustrates Python's naming conventions: snake_case for variables and functions, PascalCase for classes, CONSTANT_CASE for constants, and a leading underscore for private members.
```python
# Variables and functions: snake_case
user_name = 'Alice'
def get_user_posts(user_id):
pass
# Classes: PascalCase
class UserService:
pass
# Constants: CONSTANT_CASE
MAX_RETRIES = 3
# Private members: leading underscore
class User:
_private_field = 'private'
__name_mangled = 'private' # Name mangling
```
--------------------------------
### Set Function to Assign Value
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use `set` to mutate state from a current value to a new value declaratively. The pattern is `set` + context.
```javascript
let fruits = 0
function setFruits(nextFruits) {
fruits = nextFruits
}
setFruits(5)
console.log(fruits)
```
--------------------------------
### Decision Tree for Singular vs. Plural Naming
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use singular names for variables holding exactly one value and plural names for variables holding zero or more values.
```text
How many values can the variable hold?
├─ Exactly one → use singular (user, post, item)
└─ Zero or more → use plural (users, posts, items)
```
--------------------------------
### Mixed Parameters (Single + Multiple)
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
When a function accepts both single values and collections, use singular names for single-value parameters and plural names for collection parameters to maintain clarity.
```javascript
// Single + Multiple
function findFriendsOfUser(user, allUsers) {
// `user` is singular: one entity
// `allUsers` is plural: collection
return allUsers.filter(u => u.id !== user.id)
}
// Correct naming makes intent clear without documentation
```
--------------------------------
### Prefix Modifiers for Naming
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/README.md
Employ these prefixes to denote characteristics, possession, conditions, boundaries, or state transitions.
```text
| Prefix | Describes | Example |
|---|---|---|
| `is` | Characteristic/state | `isActive`, `isVisible` |
| `has` | Possession | `hasChildren`, `hasPermission` |
| `should` | Conditional action | `shouldRender`, `shouldRetry` |
| `min`/`max` | Boundaries | `minWidth`, `maxRetries` |
| `prev`/`next` | State transitions | `prevState`, `nextPage` |
```
--------------------------------
### Remove Redundant Domain Context in Class Methods
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Avoid repeating domain context in method names when the class itself already establishes that context. Use shorter, more direct names.
```javascript
// User management module/namespace
class UserService {
// Redundant: "User" is already the context
getUserDetails = (id) => { ... }
getUserPosts = (id) => { ... }
// Better: context is provided by the class
getDetails = (id) => { ... }
getPosts = (id) => { ... }
}
// Usage: new UserService().getDetails(123)
// The "User" context comes from UserService, not from the method name
```
--------------------------------
### Aggregate or Summary Data Naming
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Use singular names for variables that hold a single aggregate or summary of data. These variables represent one consolidated result, even if they contain multiple fields.
```javascript
// Singular when representing one aggregate
const userSummary = calculateUserMetrics(users)
const stats = computeStatistics(data)
const metadata = extractMetadata(item)
// These are single summary objects, even if they contain multiple fields
```
--------------------------------
### Singular vs. Plural Variable Naming
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/README.md
Use singular names for single values and plural names for collections. This improves code readability by clearly indicating the nature of the data stored.
```javascript
/* Bad */
const friends = 'Bob'
const friend = ['Bob', 'Tony', 'Tanya']
/* Good */
const friend = 'Bob'
const friends = ['Bob', 'Tony', 'Tanya']
```
--------------------------------
### Collection Naming: Mapped/Transformed
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use suffixes like 'Ids', 'Names', or 'Titles' for arrays that contain transformed data from a collection.
```javascript
// Mapped/Transformed
const userIds = [1, 2, 3]
const userNames = ['Alice', 'Bob']
const postTitles = ['Post 1', 'Post 2']
```
--------------------------------
### Reflect Expected Result in Boolean Variables (JavaScript)
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Use clear and direct naming for boolean variables to reflect the state that triggers a condition. Prefer positive forms or names that directly match the condition's outcome.
```javascript
// Anti-pattern: condition doesn't match name
const isNotLoggedIn = !user
if (isNotLoggedIn) renderLoginPage()
// Better: name reflects the state when condition triggers
const isLoggedOut = !user
if (isLoggedOut) renderLoginPage()
// Or use positive form
const isLoggedIn = !!user
if (!isLoggedIn) renderLoginPage()
// Best: clearest intent
const hasUser = !!user
if (!hasUser) renderLoginPage()
```
--------------------------------
### Boolean Naming: has + noun
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use 'has' prefix for boolean variables indicating the presence of something.
```javascript
// has + noun
const hasChildren = true
const hasPermission = false
const hasError = true
```
--------------------------------
### Boolean Characteristic or State with 'is'
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use the 'is' prefix for variables that describe a characteristic or current state, typically returning a boolean value.
```javascript
const color = 'blue'
const isBlue = color === 'blue' // Characteristic
const isPresent = element !== null // State
const isVisible = style.display !== 'none' // State
if (isBlue && isPresent) {
console.log('Blue is present!')
}
```
```javascript
const isString = typeof value === 'string'
const isNumeric = !isNaN(value)
const isEven = number % 2 === 0
const isPrime = checkPrime(number)
```
```javascript
const isLoading = requestInProgress === true
const isMounted = componentMounted === true
const isAuthenticated = userToken !== null
```
--------------------------------
### Anti-Pattern: Unnatural or Invented Words
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Do not use unnatural-sounding words like 'paginatable' or invented verbs like 'paginatize'. These violate the Intuitive and Descriptive principles, making the code sound unnatural and hard to understand.
```javascript
const isPaginatable = a > 10
// ✗ Sounds unnatural; "paginatable" is not a recognized English word
// - Short ✓ but not intuitive or descriptive
const shouldPaginatize = a > 10
// ✗ Made-up verb; not found in English
// - Short ✓ but not intuitive or descriptive
```
--------------------------------
### Generic Collection Names (Preferred)
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Use generic names for collections when the data structure is not semantically important. This allows for implementation changes without affecting the caller and focuses the name on the data's meaning.
```javascript
// Generic: name doesn't specify data structure
const users = getUsersFromDatabase()
const activeItems = items.filter(i => i.active)
const results = processData(input)
// Benefits:
// - Implementation can change (array → set → lazy iterable)
// - Name focuses on semantic meaning, not structure
// - Works across different programming paradigms
```
--------------------------------
### Avoid Contractions in Variable Names
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Demonstrates common contractions used in variable names that reduce readability and can cause ambiguity. Use full words instead.
```javascript
const onItmClk = () => { } // Should be: onItemClick
const getFrndList = () => { } // Should be: getFriendList
const isAvlbl = true // Should be: isAvailable
const userPrfs = { } // Should be: userPrefs (still contracted)
```
--------------------------------
### Grouped/Categorized Data Naming
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
When data is grouped or categorized, use plural names for the resulting structure. This signifies that the container holds multiple distinct groups.
```javascript
// Plural: represents multiple groupings
const usersByRole = groupBy(users, 'role')
const postsByCategory = groupBy(posts, 'category')
// Even though the container is one object, it semantically represents
// multiple categorizations/groupings
```
--------------------------------
### Context/Scope Patterns: Removing Unnecessary Context
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
If a variable's context is already established (e.g., within a user object), avoid redundant naming like 'userName'.
```javascript
// Removing unnecessary context
const userName = 'Alice' // ✗ If already in user object
const user = { name: 'Alice' } // ✓ Context in object
```
--------------------------------
### Boolean Collections Naming
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Use plural names for arrays of booleans representing multiple flags or states. For objects grouping boolean attributes, use plural names if they represent a collection of features.
```javascript
// Plural: representing multiple flags/states
const flags = [true, false, true, true]
const conditions = [condition1, condition2, condition3]
// But when grouping boolean attributes:
const userFeatures = {
hasNotification: true,
hasPreferences: false,
hasProfile: true
}
// Still plural because it's a collection of features, but the container is singular
```
--------------------------------
### Single Value Parameter
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Name function parameters with singular nouns when they are expected to receive a single value or entity.
```javascript
function getName(user) {
return user.name
}
function deleteComment(comment) {
database.remove(comment)
}
```
--------------------------------
### Anti-Pattern: Meaningless Variable Names
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Avoid single-letter variable names like 'a' as they are meaningless and violate the Short, Intuitive, and Descriptive principles. They require external context to understand their purpose.
```javascript
const a = 5
// ✗ "a" violates all three principles: it is meaningless
// - Not short in intent (requires context to understand)
// - Not intuitive (conveys no meaning)
// - Not descriptive (could mean anything)
```
--------------------------------
### Specific Collection Names
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Use specific names when the container type is semantically important, multiple containers of the same entity exist, or the container's behavior (FIFO, LIFO, unordered) matters to the caller.
```javascript
// Specific: name includes container type
const userIds = [1, 2, 3] // Array of IDs
const userSet = new Set(users) // Explicitly a Set
const userQueue = new Queue() // Queue data structure
const userMap = new Map() // Map/dictionary structure
// Use when:
// - Container type is semantically important
// - Multiple containers of same entity type exist
// - Container behavior (FIFO, LIFO, unordered) matters to caller
```
--------------------------------
### Dictionary/Map Naming Convention
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Dictionaries and maps are conventionally named in the plural, even though they represent a single object. This reflects the multiple key-value mappings they contain.
```javascript
// Plural naming for dictionaries is standard
const userById = new Map() // Maps user IDs to user objects
const messagesByUserId = {} // Object acting as dictionary
// Rationale: semantically represent multiple mappings
userById.set(1, new User('Alice'))
userById.set(2, new User('Bob'))
// Read as "users by id" — multiple user-id associations
```
--------------------------------
### Reflect Expected Result in Boolean Variables (JSX)
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Name boolean variables to match the expected state that triggers an action, rather than the inverse condition. This avoids mental inversion when used with props.
```jsx
const isEnabled = itemCount > 3
return
```
```jsx
const isDisabled = itemCount <= 3
return
```
--------------------------------
### Correct Pattern: Multiple Values
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Use a plural name for variables holding multiple values, such as arrays or collections. This clearly indicates that iteration, length checks, and indexed access are appropriate.
```javascript
/* Good */
const friends = ['Bob', 'Tony', 'Tanya']
// Type is immediately clear
for (const friend of friends) { // ✓ Iterate over collection
console.log(friend.name)
}
const count = friends.length // ✓ Get collection size
const first = friends[0] // ✓ Access first friend
```
--------------------------------
### Delete Function to Erase Completely
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use `delete` for complete erasure with permanent implications. It does not require a collection destination and pairs with `create`. This operation is difficult to reverse.
```javascript
function deletePost(id) {
return database.find({ id }).delete()
}
```
--------------------------------
### Use English for Identifiers
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Always use English for variable and function names, regardless of your native language, to align with programming language syntax and industry standards.
```javascript
// Spanish
const primerNombre = 'Gustavo'
const amigos = ['Kate', 'John']
// French
const prenom = 'Gustavo'
// German
const freunde = ['Kate', 'John']
```
```javascript
const firstName = 'Gustavo'
const friends = ['Kate', 'John']
```
--------------------------------
### Consistent snake_case Convention
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Apply the snake_case convention consistently for all variables and functions to ensure uniformity and clarity.
```javascript
/* Also good — all snake_case */
const page_count = 5
const should_update = true
const max_retries = 3
const final_result = true
```
--------------------------------
### Context order 2: Entity as high context
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/03-function-naming-pattern.md
Use when the component controls its own update logic. The interpretation is 'The component should decide whether to update itself'.
```javascript
// Context order 2: Entity as high context
shouldComponentUpdate(nextProps, prevProps)
// Interpretation: "The component should decide whether to update itself"
// The component controls its own update logic
// Example use: if (this.shouldComponentUpdate(next, prev)) { ... }
```
--------------------------------
### Boolean Naming: is + adjective
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use 'is' or 'has' prefixes for boolean variables that represent a state or property. 'is' is typically used with adjectives, 'has' with nouns.
```javascript
// is + adjective
const isActive = true
const isVisible = false
const isValid = true
const isDisabled = false
```
--------------------------------
### Multiple Values Parameter
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Name function parameters with plural nouns when they are expected to receive a collection of values or entities. This clearly indicates that the function operates on multiple items.
```javascript
function filterUsers(users, criteria) {
// `users` is plural: expected to be collection
return users.filter(u => matchesCriteria(u, criteria))
}
function deleteComments(comments) {
// `comments` is plural: expected to be collection
return comments.forEach(c => database.remove(c))
```
--------------------------------
### Correct Pattern: Single Value
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/04-cardinality-conventions.md
Use a singular name for variables holding a single value. This makes the type immediately clear and allows for correct string operations and single value checks.
```javascript
/* Good */
const friend = 'Bob'
// Type is immediately clear
const firstName = friend.split(' ')[0] // ✓ String operation on string
if (friend) { ... } // ✓ Single value check
```
--------------------------------
### Collection Naming: Filtered Results
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/05-naming-glossary.md
Use descriptive adjectives or status indicators as prefixes for arrays containing filtered subsets of data.
```javascript
// Filtered results
const activeUsers = []
const publishedPosts = []
const archivedItems = []
```
--------------------------------
### Avoid Duplicated Context in Class Methods
Source: https://github.com/kettanaito/naming-cheatsheet/blob/main/_autodocs/02-core-principles.md
Remove redundant context from a name if the containing class already provides it. This reduces noise and improves readability.
```javascript
class MenuItem {
// "MenuItem" is the class context; repeating it in the method is redundant
handleMenuItemClick = (event) => {
console.log('Clicked menu item')
}
// Also redundant
menuItemIsVisible = false
currentMenuItemState = 'active'
}
```
```javascript
class MenuItem {
// Reads as `MenuItem.handleClick()` — context is clear
handleClick = (event) => {
console.log('Clicked menu item')
}
// "MenuItem" context is implicit
isVisible = false
currentState = 'active'
}
```