JavaScript Best Practices and Preferences

Getting things done is good but getting things done in better way is what matters most. Everyone wants to make their website to be faster, lighter. No one likes slow website. In order to make our website faster we have to set some best practices standards and every teammate should follow that.
I have written down few of the best practices which I recommend to be followed in any JavaScript development.
Performance
- VanillaJS is always quicker than using a library. Use VanillaJS as possible if you want highest performance.
- Minimize DOM manipulation since it is a performance consuming task.
- Minimize number of HTTP calls. Try to use cached HTTP response.
- Use lazy loading of resources as much as feasible.
- Avoid broadcasting and listening the events.
- Avoid adding global variables and global methods.
- Use
{}
instead ofnew Object()
. - Use
[]
instead ofnew Array()
. - Declare variables outside of loop.
- Place scripts at the bottom of your web page.
- It will help in speeding up the web page loading.
Risks
eval
= Evil
With great power, comes great responsibility.
Eval is very powerful feature of JavaScript, hence it requires to be used very carefully. It can produce an enormous security risk.
2. Use ===
instead of ==
- It makes sure that comparison is type safe.
3. Whenever we create any variable, we should try to make it as private as possible. It will help us to avoid name collision with global variables and will provide encapsulation.
4. Use editor plug-in for JS Hint. It will highlight many errors and warnings which will help us to avoid bugs.
5. Add null/undefined
checks wherever possible.
6. The JSON.parse method should be enclosed in a try-catch block to prevent the application from crashing if an incomplete or malformed string is passed to it.
Organised Codebase
- One file = One Responsibility.
- Don’t use short-hand. Even though there is only one statement in a condition block or loop block, it should be enclosed by curly braces.
3. Use configuration instead of hard coding.
4. For defining strings, use single quotes instead of double quotes.
5. Add comments on method level and conditions (if conditions are complex).
6. Always use semicolons to end the statement.
7. Separate file names with dots and dashes.
8. Remove unused and commented code. Remove unused libraries and their references.