50 JavaScript Best Practice Rules to Write Better Code
--
JavaScript is powerful and flexible which allows you to code any way you like and try some very unusual things which can lead to a bug in your code. Here are 50 things I learned about coding in JavaScript you should know about.
Always “use strict” On
Chances are that if you are using any library/framework or compiler for your JavaScript, “use strict” is on but just in case you are not, remember to add it to the file and to the functions. It will make sure you get errors that would happen silently if you don't include it.
Use Function expressions instead of Function Declarations
Unless you want to take advantage of Function behavior and properties, prefer function expressions. Function declarations are hoisted and although it can be useful sometimes, avoid them as they introduce weird behavior to the code and it is not always obvious what's happening. Try to make it clear where the function you are using comes from and they come before you use them to avoid weird access.
Stop using “var”!
Declarations with “var” are also hoisted which makes var declarations accessible before where the declaration happened which is weird, non-obvious behavior.
Use “const” and immutability as much as possible
Prefer immutability as much as possible. Constantly changing data and passing it around can make it hard to track bugs and the changes themselves. Work on data copies and avoid side effects.
Prefer Pure Functions
Continuing on the side effect note, ensure your functions are not changing data they are called with or data in the scope where they are created.