1. Indentation
- Use Tabs: Indentation must be done with tabs, not spaces, to ensure consistency across environments.
2. Quotes
- Single Quotes: Use single quotes for strings, and only use double quotes for HTML attributes.
3. Naming Conventions
- CamelCase: Use
camelCase
for variables and functions, and PascalCase
for constructors.
4. Line Length
- 80 Characters: Aim to keep each line of code within 80 characters. Break lines that are too long.
5. Comments
- Use Clear Comments: Write comments to explain why the code exists, not what it does.
6. Equality Checks
- Strict Equality: Always use
===
and !==
to avoid unexpected type coercion.
7. JSDoc Comments
- Document Your Code: Use JSDoc to describe the purpose of functions and their parameters.
8. Spacing
- Consistent Spacing: Maintain spacing around operators and after commas for clarity.
9. Array and Object Literals
- Readable Structure: Break complex array and object literals across multiple lines.
10. Avoid Global Variables
- Encapsulation: Encapsulate your code in IIFEs (Immediately Invoked Function Expressions) or modules to avoid polluting the global namespace.
11. Use let
and const
- Block Scoping: Use
let
for variables that may change and const
for constants to leverage block scoping and avoid issues with variable hoisting.
Let's dive even deeper into WordPress JavaScript coding standards:
12. Function Declarations vs. Expressions
- Function Declarations: Use function declarations for named functions, which helps in hoisting and improves readability.
- Function Expressions: Use function expressions for anonymous functions, especially for callbacks.
13. IIFE (Immediately Invoked Function Expressions)
- Scope Isolation: Use IIFE to create a private scope, preventing conflicts with other scripts.
14. Object-Oriented Programming (OOP)
- Classes and Prototypes: Embrace ES6 classes for object-oriented patterns.
15. Error Handling
- Try-Catch: Use
try-catch
blocks for error-prone operations like JSON parsing or external API calls.
16. Modularization
- Modular Code: Organize code into modules or files to promote reusability and maintainability.
17. Event Handling
- Use Delegation: Event delegation can improve performance, especially with dynamic content.
18. DOM Manipulation
- Minimize Direct Manipulation: Use functions like
document.createElement
and appendChild
instead of innerHTML to avoid XSS vulnerabilities.
19. Performance Considerations
- Debounce or Throttle: Use debounce or throttle techniques for event handlers like scroll or resize to improve performance.
20. Security Practices
- Sanitize Inputs: Always sanitize user inputs to prevent XSS and other security vulnerabilities.