Here’s the most readable JavaScript code example with best practices, comprehensive documentation, and excellent structure
Key readability features demonstrated:
✅ Comprehensive file header - Project overview and author info ✅ Section dividers - Clear organization with ========== separators ✅ JSDoc comments - Every class and method fully documented ✅ Clear naming - Descriptive names with underscore prefix for private methods ✅ Meaningful variable names - isModified instead of mod, nextId instead of nid ✅ Consistent formatting - 8-space indentation, consistent spacing ✅ Input validation - Comprehensive validation with descriptive error messages ✅ Error handling - Clear error messages and status codes ✅ Private/public separation - Methods prefixed with _ are internal ✅ Constants at top - Configuration centralized in CONFIG object ✅ Logical grouping - Related code organized in classes and sections ✅ Examples in comments - Usage examples in JSDoc ✅ Defensive programming - Type checks and null/undefined handling ✅ Return value clarity - Consistent object return format with status ✅ Method chaining ready - Objects returned for potential chaining ✅ Modern ES6+ - Classes, const/let, arrow functions, template literals
This style makes JavaScript code self-documenting and easy to maintain!
/**
* =============================================================================
* PROJECT: Data Management System
* AUTHOR: AndrewMaksimchuk
* DATE: 2026-03-23
* PURPOSE: Demonstrate highly readable JavaScript code with clear structure,
* comprehensive comments, meaningful naming, and best practices.
* =============================================================================
*/
'use strict';
/**
* =============================================================================
* CONSTANTS AND CONFIGURATION
* =============================================================================
*/
const CONFIG = {
MAX_NAME_LENGTH: 64,
MAX_EMAIL_LENGTH: 128,
MAX_PHONE_LENGTH: 20,
MAX_DESCRIPTION_LENGTH: 256,
MAX_RECORDS: 1000,
MIN_AGE: 18,
MAX_AGE: 150,
EMAIL_REGEX: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
PHONE_REGEX: /^[\d\s\-\(\)]+$/,
};
const STATUS = {
SUCCESS: 'success',
FAILURE: 'failure',
VALIDATION_ERROR: 'validation_error',
NOT_FOUND: 'not_found',
};
/**
* =============================================================================
* DATA STRUCTURES / CLASSES
* =============================================================================
*/
/**
* PersonRecord class
*
* Represents a single person with contact information and metadata.
* Encapsulates all data for a person record with validation.
*
* @example
* const person = new PersonRecord({
* id: 1,
* name: 'Alice Johnson',
* email: 'alice@example.com',
* phone: '555-1234',
* age: 28,
* isActive: true
* });
*/
class PersonRecord {
/**
* Creates a new PersonRecord instance
*
* @param {Object} data - The data object containing person information
* @param {number} data.id - Unique identifier (auto-generated)
* @param {string} data.name - Person's full name
* @param {string} data.email - Person's email address
* @param {string} data.phone - Person's phone number
* @param {number} data.age - Person's age in years
* @param {boolean} data.isActive - Whether record is active
* @throws {Error} If required fields are missing or invalid
*/
constructor(data = {}) {
this.id = data.id || null;
this.name = data.name || '';
this.email = data.email || '';
this.phone = data.phone || '';
this.age = data.age || 0;
this.isActive = data.isActive !== undefined ? data.isActive : true;
this.createdAt = data.createdAt || new Date();
this.updatedAt = data.updatedAt || new Date();
}
/**
* Returns a deep copy of this record
*
* @returns {PersonRecord} A new PersonRecord with copied data
*/
clone() {
return new PersonRecord({
id: this.id,
name: this.name,
email: this.email,
phone: this.phone,
age: this.age,
isActive: this.isActive,
createdAt: new Date(this.createdAt),
updatedAt: new Date(this.updatedAt),
});
}
/**
* Converts record to plain JavaScript object
*
* @returns {Object} Plain object representation of the record
*/
toJSON() {
return {
id: this.id,
name: this.name,
email: this.email,
phone: this.phone,
age: this.age,
isActive: this.isActive,
createdAt: this.createdAt.toISOString(),
updatedAt: this.updatedAt.toISOString(),
};
}
/**
* Returns a formatted string representation of the record
*
* @returns {string} Formatted display string
*/
toString() {
return `PersonRecord(id=${this.id}, name="${this.name}", email="${this.email}")`;
}
}
/**
* PersonDataStore class
*
* Central data storage container managing all person records.
* Provides methods for CRUD operations, validation, and querying.
*
* @example
* const store = new PersonDataStore();
* store.addRecord('Alice', 'alice@example.com', '555-1234', 28);
* const person = store.findById(1);
*/
class PersonDataStore {
/**
* Creates a new PersonDataStore instance
*
* @param {Object} options - Configuration options
* @param {number} options.maxRecords - Maximum number of records to store
*/
constructor(options = {}) {
this.records = [];
this.maxRecords = options.maxRecords || CONFIG.MAX_RECORDS;
this.nextId = 1;
this.isModified = false;
this.lastErrorMessage = '';
}
/**
* Clears all error state
*
* @private
* @returns {void}
*/
_clearError() {
this.lastErrorMessage = '';
}
/**
* Sets an error message
*
* @private
* @param {string} message - The error message to set
* @returns {void}
*/
_setError(message) {
this.lastErrorMessage = message;
console.error(`[DataStore Error]: ${message}`);
}
/**
* Validates a person's name
*
* @param {string} name - The name to validate
* @returns {Object} Validation result with { isValid: boolean, error?: string }
*/
_validateName(name) {
if (typeof name !== 'string') {
return { isValid: false, error: 'Name must be a string' };
}
if (name.trim().length === 0) {
return { isValid: false, error: 'Name cannot be empty' };
}
if (name.length > CONFIG.MAX_NAME_LENGTH) {
return {
isValid: false,
error: `Name exceeds maximum length of ${CONFIG.MAX_NAME_LENGTH}`,
};
}
return { isValid: true };
}
/**
* Validates an email address using regex pattern
*
* @param {string} email - The email to validate
* @returns {Object} Validation result with { isValid: boolean, error?: string }
*/
_validateEmail(email) {
if (typeof email !== 'string') {
return { isValid: false, error: 'Email must be a string' };
}
if (!CONFIG.EMAIL_REGEX.test(email)) {
return { isValid: false, error: 'Email format is invalid' };
}
return { isValid: true };
}
/**
* Validates a phone number
*
* @param {string} phone - The phone number to validate
* @returns {Object} Validation result with { isValid: boolean, error?: string }
*/
_validatePhone(phone) {
if (typeof phone !== 'string') {
return { isValid: false, error: 'Phone must be a string' };
}
if (phone.trim().length < 10) {
return { isValid: false, error: 'Phone number must have at least 10 digits' };
}
if (!CONFIG.PHONE_REGEX.test(phone)) {
return { isValid: false, error: 'Phone number contains invalid characters' };
}
return { isValid: true };
}
/**
* Validates a person's age
*
* @param {number} age - The age to validate
* @returns {Object} Validation result with { isValid: boolean, error?: string }
*/
_validateAge(age) {
if (typeof age !== 'number' || !Number.isInteger(age)) {
return { isValid: false, error: 'Age must be an integer' };
}
if (age < CONFIG.MIN_AGE) {
return { isValid: false, error: `Age must be at least ${CONFIG.MIN_AGE}` };
}
if (age > CONFIG.MAX_AGE) {
return { isValid: false, error: `Age cannot exceed ${CONFIG.MAX_AGE}` };
}
return { isValid: true };
}
/**
* Adds a new person record to the data store
*
* Validates all input before insertion and assigns unique ID.
*
* @param {string} name - Person's name
* @param {string} email - Person's email
* @param {string} phone - Person's phone number
* @param {number} age - Person's age
* @returns {Object} Result object with { status, recordId?, error? }
*
* @example
* const result = store.addRecord('Alice', 'alice@example.com', '555-1234', 28);
* if (result.status === 'success') {
* console.log(`Added record with ID: ${result.recordId}`);
* }
*/
addRecord(name, email, phone, age) {
this._clearError();
// Validate all inputs
const nameValidation = this._validateName(name);
if (!nameValidation.isValid) {
this._setError(nameValidation.error);
return { status: STATUS.VALIDATION_ERROR, error: nameValidation.error };
}
const emailValidation = this._validateEmail(email);
if (!emailValidation.isValid) {
this._setError(emailValidation.error);
return { status: STATUS.VALIDATION_ERROR, error: emailValidation.error };
}
const phoneValidation = this._validatePhone(phone);
if (!phoneValidation.isValid) {
this._setError(phoneValidation.error);
return { status: STATUS.VALIDATION_ERROR, error: phoneValidation.error };
}
const ageValidation = this._validateAge(age);
if (!ageValidation.isValid) {
this._setError(ageValidation.error);
return { status: STATUS.VALIDATION_ERROR, error: ageValidation.error };
}
// Check storage capacity
if (this.records.length >= this.maxRecords) {
const error = 'Record store is at maximum capacity';
this._setError(error);
return { status: STATUS.FAILURE, error };
}
// Create new record
const newRecord = new PersonRecord({
id: this.nextId++,
name: name.trim(),
email: email.toLowerCase().trim(),
phone: phone.trim(),
age,
isActive: true,
});
this.records.push(newRecord);
this.isModified = true;
console.log(`✓ Record added successfully with ID: ${newRecord.id}`);
return { status: STATUS.SUCCESS, recordId: newRecord.id };
}
/**
* Finds a record by its unique ID
*
* @param {number} recordId - The ID to search for
* @returns {PersonRecord|null} The found record or null if not found
*/
findById(recordId) {
return this.records.find(record => record.id === recordId) || null;
}
/**
* Finds all records matching a name (case-insensitive partial match)
*
* @param {string} name - The name to search for
* @returns {Array<PersonRecord>} Array of matching records
*/
findByName(name) {
const searchTerm = name.toLowerCase().trim();
return this.records.filter(record =>
record.name.toLowerCase().includes(searchTerm)
);
}
/**
* Finds a record by email address
*
* @param {string} email - The email to search for
* @returns {PersonRecord|null} The found record or null if not found
*/
findByEmail(email) {
const searchTerm = email.toLowerCase().trim();
return this.records.find(record =>
record.email.toLowerCase() === searchTerm
) || null;
}
/**
* Removes a record from the store by ID
*
* @param {number} recordId - The ID of the record to remove
* @returns {Object} Result object with { status, removed?: boolean }
*/
removeRecord(recordId) {
const index = this.records.findIndex(record => record.id === recordId);
if (index === -1) {
const error = `Record with ID ${recordId} not found`;
this._setError(error);
return { status: STATUS.NOT_FOUND, error };
}
const removedRecord = this.records.splice(index, 1)[0];
this.isModified = true;
console.log(`✓ Record removed: ${removedRecord.toString()}`);
return { status: STATUS.SUCCESS, removed: true };
}
/**
* Deactivates a record (soft delete)
*
* @param {number} recordId - The ID of the record to deactivate
* @returns {Object} Result object with { status, error? }
*/
deactivateRecord(recordId) {
const record = this.findById(recordId);
if (!record) {
const error = `Record with ID ${recordId} not found`;
this._setError(error);
return { status: STATUS.NOT_FOUND, error };
}
record.isActive = false;
record.updatedAt = new Date();
this.isModified = true;
console.log(`✓ Record deactivated: ${record.toString()}`);
return { status: STATUS.SUCCESS };
}
/**
* Returns all active records
*
* @returns {Array<PersonRecord>} Array of all active records
*/
getAllRecords() {
return this.records.filter(record => record.isActive);
}
/**
* Gets the total count of records
*
* @returns {number} Total number of records in store
*/
getRecordCount() {
return this.records.length;
}
/**
* Gets the count of active records only
*
* @returns {number} Number of active records
*/
getActiveRecordCount() {
return this.records.filter(record => record.isActive).length;
}
/**
* Calculates the average age of all active records
*
* @returns {number} Average age or 0 if no records
*/
getAverageAge() {
const activeRecords = this.getAllRecords();
if (activeRecords.length === 0) return 0;
const totalAge = activeRecords.reduce((sum, record) => sum + record.age, 0);
return Math.round(totalAge / activeRecords.length);
}
/**
* Exports all records as JSON array
*
* @returns {Array<Object>} Array of record objects in JSON format
*/
exportAsJSON() {
return this.getAllRecords().map(record => record.toJSON());
}
/**
* Displays all records in formatted table
*
* @returns {void}
*/
displayAll() {
const activeRecords = this.getAllRecords();
if (activeRecords.length === 0) {
console.log('No records to display');
return;
}
console.log('\n========================================');
console.log(` ALL RECORDS (${activeRecords.length} total)`);
console.log('========================================\n');
activeRecords.forEach(record => {
console.log(`ID: ${record.id}`);
console.log(`Name: ${record.name}`);
console.log(`Email: ${record.email}`);
console.log(`Phone: ${record.phone}`);
console.log(`Age: ${record.age}`);
console.log('---');
});
console.log('========================================\n');
}
}
/**
* =============================================================================
* APPLICATION ENTRY POINT
* =============================================================================
*/
/**
* Main application function
*
* Demonstrates usage of the PersonDataStore with sample data
*
* @returns {void}
*/
function main() {
console.log('=== Data Management System ===\n');
// Initialize data store
const store = new PersonDataStore({
maxRecords: 1000,
});
// Add sample records
const records = [
{ name: 'Alice Johnson', email: 'alice@example.com', phone: '555-1234', age: 28 },
{ name: 'Bob Smith', email: 'bob@example.com', phone: '555-5678', age: 35 },
{ name: 'Carol White', email: 'carol@example.com', phone: '555-9012', age: 32 },
{ name: 'David Brown', email: 'david@example.com', phone: '555-3456', age: 45 },
];
console.log('Adding records...\n');
records.forEach(data => {
const result = store.addRecord(data.name, data.email, data.phone, data.age);
if (result.status === STATUS.SUCCESS) {
console.log(` ✓ Added: ${data.name}`);
}
});
// Display all records
console.log('');
store.displayAll();
// Display statistics
console.log('Statistics:');
console.log(` Total Records: ${store.getRecordCount()}`);
console.log(` Active Records: ${store.getActiveRecordCount()}`);
console.log(` Average Age: ${store.getAverageAge()} years\n`);
// Find specific record
console.log('Finding records:');
const alice = store.findByEmail('alice@example.com');
if (alice) {
console.log(` ✓ Found: ${alice.toString()}\n`);
}
// Deactivate a record
console.log('Deactivating record...');
store.deactivateRecord(2);
// Final display
console.log('\nFinal state:');
console.log(` Total Records: ${store.getRecordCount()}`);
console.log(` Active Records: ${store.getActiveRecordCount()}`);
}
// Run application
if (typeof module !== 'undefined' && module.exports) {
module.exports = { PersonRecord, PersonDataStore };
}
main();