Best Practices for JS

Write code for your later self and for your co-workers in the first place - not for the machine

Avoid Global Variables

Global variables and functions can be overwritten by other scripts

Initialize Variables

  • Avoid undefined values
  • Give cleaner code
  • Provide a single place to initialize variables

Never Declare Number, String, or Boolean objects

Using these types as objects, causes:

  • Slows down execution speed
  • Side effects

Don't Use new Object

  • Use {} instead of new Object()
  • Use "" instead of new String()
  • Use 0 instead of new Number()
  • Use false instead of new Boolean()
  • Use [] instead of new Array()
  • Use /()/ instead of new RegExp()
  • Use function (){} instead of new Function()

Use === Comparison

Make it Understandable

Choose easy to understand and short names for variables and functions.

Comment as Much as Needed but not more

“Good code explains itself” is an arrogant myth.

Use Shortcut Notations

Shortcut notations keep your code snappy and easier to read once you get used to it.

Avoid long argument list

Use a single object parameter and destructuring assignment instead. It also makes handling optional parameters much easier.

Reduce side effects

Use pure functions without side effects, whenever you can. They are really easy to use and test.

Write tests

  • Unit tests
  • Integration tests
  • Acceptance tests

Follow a Code Style

Use a linter

Read, Read, Read!

Made with Slides.com