JavaScript Best Practices — Basic Syntax

John Au-Yeung
Level Up Coding
Published in
4 min readJul 5, 2020

--

Photo by Phil Hearing on Unsplash

Like any kind of app, JavaScript apps also have to be written well. Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some best practices we should follow when writing JavaScript code.

Indentation

We should have 2 spaces for indentation. This minimizes typing while maintaining visibility.

For instance, we write:

function hello (name) {
console.log('hi')
}

Single Quotes for Strings

Single quotes are good for delimiting strings since we don't have to press the shift key as we do with typing double-quotes.

For instance, we can write:

'hello world'

to save us some effort when typing.

No Unused Variables

Variables we don’t use are useless, so we shouldn’t have them.

Add a Space After Keywords

A space after keywords is always useful since it makes reading our code easier.

So we should add them:

if (condition) { ... }

Having no spaces make things hard to read.

Add a Space Before a Function Declaration’s Parentheses

We should add a space before a function declaration’s parentheses for better readability,

For example, we should write:

function foo (arg) { ... }

Always Use === Instead of ==

=== doesn’t to automatic data type conversions with complex rules before comparing its operands.

Therefore, this makes === much more preferable than == .

It’ll help us avoid lots of bugs by using it.

So we write:

if (name === 'james')

instead of:

if (name == 'james')

Likewise, we should use !== instead of != for inequality comparison for the same reason.

--

--