JavaScript for LWC

Coding Conventions and Style Guidelines


Coding conventions and style guidelines are a set of agreed-upon rules and practices that developers follow to ensure consistency and readability in their code. Following these conventions makes your code easier to understand, maintain, and collaborate on. In the context of Lightning Web Components (LWC), adhering to coding conventions and style guidelines is essential for creating clean and maintainable code. We'll explore each guideline in more detail and provide examples for better understanding.


Coding Conventions and Style Guidelines

1. Consistent Naming:

Use meaningful and descriptive names for variables, functions, and components. This helps others (and your future self) understand the purpose of each element in your code.

Example:

Before:

const F = ['Account.Name', 'Account.Type', 'Account.Industry'];

After:

const fieldsToFetch = ['Account.Name', 'Account.Type', 'Account.Industry'];

2. Indentation and Formatting:

Maintain consistent indentation and formatting throughout your code. Properly indent code blocks to improve readability.

Example:

Before:

if (condition) {
if (anotherCondition) {
return 'Success';
}
}

After:

if (condition) {
    if (anotherCondition) {
        return 'Success';
    }
}

3. Comments:

Add comments to explain complex logic, assumptions, or any non-obvious behavior in your code. Comments provide context and make your code easier to understand.

Example:

Before:

// Calculate the total
total = price * quantity;

After:

// Calculate the total by multiplying price and quantity
total = price * quantity;

4. Use Constants:

Use constants to define values that are reused throughout your code. This improves readability and makes changes easier.

Example:

Before:

const pageSize = 10;

After:

const PAGE_SIZE = 10;

5. Consistent Component Structure:

Organize your component's structure in a consistent manner. Separate different parts of your component (HTML, JavaScript, CSS) into their respective sections.

Example:

Before:

export default class MyComponent extends LightningElement {
    // ...
}

After:

export default class MyComponent extends LightningElement {
    // Component logic (JavaScript)
    // ...

    // Component template (HTML)
    // ...

    // Component styles (CSS)
    // ...
}

6. Limit Line Length:

Keep lines of code relatively short (around 80-100 characters) to improve readability. Long lines can be difficult to read and understand, especially during code reviews.

Example:

Before:

const longString = 'This is a very long string that goes on and on and on...';

After:

const longString = 'This is a very long string that goes on ' +
    'and on and on...';

7. Avoid Nested Logic:

Minimize deeply nested if statements or loops. This simplifies your code and makes it easier to understand.

Example:

Before:

if (condition1) {
    if (condition2) {
        if (condition3) {
            // Do something
        }
    }
}

After:

if (condition1 && condition2 && condition3) {
    // Do something
}

8. Use Meaningful Variable Names:

Choose variable names that clearly convey their purpose. This enhances code readability and reduces the need for comments to explain the purpose of variables.

Example:

Before:

const x = 5;

After:

const numberOfItems = 5;

By following these coding conventions and style guidelines, you'll create code that is not only easier to read and understand but also more maintainable and collaborative. Consistency in your code style helps make your development process smoother and more enjoyable.


 MIND IT !

Let's put together an example of a Lightning Web Component (LWC) that incorporates various coding conventions and style guidelines that we've discussed earlier.

Here's a comprehensive example of a Lightning Web Component (LWC) that incorporates a wide range of coding conventions and style guidelines. Please note that this example is quite extensive to cover as many guidelines as possible in a single example. In a real-world scenario, you might not see all these guidelines applied to a single component.






import { LightningElement, wire, track } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';

const CONTACT_FIELDS = ['Name', 'Email'];

export default class ContactListComponent extends LightningElement {
    @track contacts = [];
    @track error;

    @wire(getContacts)
    wiredContacts({ error, data }) {
        if (data) {
            this.contacts = data.map((contact) => ({
                Id: contact.Id,
                Name: contact.Name,
                Email: contact.Email
            }));
            this.error = undefined;
        } else if (error) {
            this.contacts = [];
            this.error = 'An error occurred while fetching contacts.';
        }
    }

    get hasContacts() {
        return this.contacts.length > 0;
    }

    handleRefresh() {
        this.contacts = [];
        this.error = undefined;
        getContacts({})
            .then((data) => {
                this.contacts = data.map((contact) => ({
                    Id: contact.Id,
                    Name: contact.Name,
                    Email: contact.Email
                }));
            })
            .catch((error) => {
                this.error = 'An error occurred while refreshing contacts.';
            });
    }
}

Key Points Demonstrating Coding Conventions and Style Guidelines:

1. Consistent Naming:
• Component name: `ContactListComponent`
• Constant: `CONTACT_FIELDS`

2. Indentation and Formatting:
• Proper indentation for HTML and JavaScript code.

3. Comments:
• Inline comments explain the purpose of various sections and methods.

4. Use Constants:
• `CONTACT_FIELDS` constant holds the list of fields to fetch from the server.

5. Consistent Component Structure:
• Separation of concerns with clear sections for HTML, JavaScript, and CSS (not shown in the example).

6. Limit Line Length:
• Lines of code are kept within a reasonable length for readability.

7. Avoid Nested Logic:
• Simplified logic for handling errors and processing data from the server.

8. Use Meaningful Variable Names:
• Variable names like `contacts`, `error`, and `hasContacts` are self-explanatory.

9. Conditional Styling:
• Conditional classes are applied to alternate list items (`even` and `odd`).

10. Interactivity and Event Handling:
• Button click triggers the `handleRefresh` method.

11. Promises and Error Handling:
• Promises are used for fetching data with error handling.

12. Tracking Decorator:
• `@track` decorator is used for reactive data binding.


This comprehensive example showcases how various coding conventions and style guidelines can be applied to a Lightning Web Component, resulting in clean, readable, and maintainable code. Remember that in a real-world scenario, you might focus on a subset of these guidelines based on your specific project and team's preferences.