50 Javascript Best Practice Rules to Write Better Code

Image for post
Image for post

Always “use strict” On

Image for post
Image for post

Use Function expressions instead of Function Declarations

Image for post
Image for post

Stop using “var”!

Use “const” and immutability as much as possible

Prefer Pure Functions

Image for post
Image for post

Prefer Class over Constructor Functions

Use “destructuring”

Image for post
Image for post

Only work with data you need

Always use “===”

Avoid Global Variables

Wrap loose declarations in blocks

Image for post
Image for post

Organize your declarations

Don't initialize things with “undefined”

Always initialize your declarations

Lint your code and have a consistent style

Use Typescript

Functions and methods should do one thing only

Image for post
Image for post

Don’t be lazy when naming things

Avoid unnecessary declarations

Use default values when posible

Always have a default case for switch statements

Never use “eval”

Avoid the “new” keyword

Image for post
Image for post

Add meaningful comments for nonobvious things

Keep ternaries simple

Simplify with optional chaining

Image for post
Image for post

Prefer promises over callbacks

Image for post
Image for post

For loops > .forEach sometimes

“for…in” and “for…of”

Optimize for loops

Image for post
Image for post

Always “try…catch” JSON methods

Prefer template strings

Avoid nesting or chaining loops

Avoid Weird Unreadable hacks

Prefer the “rest” operator over “arguments”

Prefer “globalThis” for global access

Understand Javascript but Build with Libraries and Frameworks

Add semicolons, always!

Readable > Performance unless you need Performance

Be careful with “Truthy” and “Falsy” checks

Image for post
Image for post

Prefer Ternary over logical “||” and “&&” checks

Image for post
Image for post

Watch out for “undefined” and “null” with the “??” operator

Be careful with automatic type conversions

Image for post
Image for post

Never trust data you don't create

Use regex when extracting and looking for things in Strings

IIFE and small utility libraries

Avoid repeating yourself with utilities

Don’t take advantage of weird Javascript “features”

Image for post
Image for post

Add Unit Tests

Written by

Blog & YouTube Channel for Web, UI & Software Development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store