Javascript Best Practices and Coding Conventions

In this video I prepared for you 10 Javascript best practices for beginners to improve your code.
Let's jump right into it.

Use camelcase

The first one is camelcase. It's the standard codestyle of Javascript so to make your code easier to read and consistend just always write camelcase. No snake case and no kebab case.

// Good
const isActive = false

// Bad
const is-active = false
const is_active = false

Naming

You code should be readable like normal English text. This means that all names of the variables should be crystal clear. So names from single letter or unreadable names that doesn't make sense of provide understanding are bad.

// Good
const article = {title: 'Some title'}
const isAlreadyPaid = true

// Bad
const a = {title: 'Some title'}
const paid = true

Also the is one important code style for booleans. It's a good practice to start boolean name with is or should. In this case we are getting from the name that this is boolean. Also we don't use are as a prefix even it sounds like incorrect English.

// Good
const isLoggedIn = true
const shouldBeRendered = true

// Bad
const logged = true
const areDefined = true

Now some point about functions namings. As the are being called we always try to start the with the verb. The only exception is for functions that return boolean

// Good
const getArticle = () => {}
const normalizeUser = () => {}
const isArticleSelected = () => {}

// Bad
const article = () => {}
const articleSelected = () => {}

And here is one more hint for you. I can recommend to always name your variables and functions less generic because it brings additional clarity.

// Bad
const data = {title: 'Some title'}

// Good
const isLoading = true
const article = {title: 'Some title'}
const url = 'http://google.com'

// Better
const isArticleLoading = true
const deleteArticleUrl = 'http://google.com'

Avoid globals

In Javascript by default all variables that we create goes to global namespace. This is dangerous because anybody can override them and we are polluting global namespace. You don't really need to write anything by yourself but just use solutions which isolate your code like webpack for example. Also if you are using any popular framework like React, Angular or Vue your code is isolated by default and you don't need to think about it.

Magic numbers

When you just start to learn Javascript you don't always have the best solution to solve your problem. This is why sometimes you have magic numbers just to fix the problem.

element.addEventListener('blur', (event) => {
  const height = event.target.height + 50
})

So here nobody knows what is 50 any why it is needed here. So it's a magic number. The best approach to write your code so, that you don't need to introduce such magic numbers. But for beginners it can be complicated so at least we should put such things an variables to make it readable for other people.

element.addEventListener('blur', (event) => {
  const padding = 25
  const heightWithPaddings = event.target.height + padding * 2
})

So here we moved padding to a variable and now we at least know what is it. Also we renamed the height to heightWithPaddings to bring understanding what is written inside.

Comments

Now I want to talk about comments. The is actually no correct answer. Some people like to write comments and say that they necessary and other say that they are not needed.

Here is my way of writing comments based on 10 years of experience and hundreds projects that I saw. We don't need to write comments to clarify what our code does. When you are doing so it means that your code is wrong or variables naming is not clear enough. We only need to write comments in a place with really tricky logic and we describe why we wrote this and not what we wrote. Also be aware that code can't be out of date because it is working but comments are not validated anywhere so you can forget to update them and they can fast get out of date.

// Bad
// We are mapping here through users to get their names

// Good
// Don't return `set.add` because it's not chainable in IE 11.

Deep nesting

Now I want to talk about nesting the code. So nesting is generally bad and should be avoided because it increases complexity of your code and decreases readability.

// BAD
const someFn = () => {
  if (someCondition) {
    if (someCondition2) {
      if (someCondition 2) {
        // some logic
      }
    }
  }
}

To solve this problem I recommend you a fail fast approach. You should try to go out of the function as easy as possible. This makes your code flat and easier to read.

// GOOD
const someFn = () => {
  if (!someCondition) {
    return 'someCondition'
  }

  if (!someCondition2) {
    return 'someCondition2'
  }

  // some logic
}

This is easier to read and support because blocks are going one by one.

Avoid long functions

It's generally a good idea to make you functions small. It doesn't mean that you should split your functions in two if you wrote more than 10 lines but your function should do only a single thing and not several of them. This is the core point.

// BAD
const someFn = () => {
  // logic to prepare data for API call

  // logic to fetch data

  // logic to normalize data
}

// good
const prepareArticleDataForAPI = () => {}
const fetchArticle = () => {}
const normalizeArticle = () => {}

const someFn = () => {
  prepareArticleDataForAPI()
  fetchArticle()
  normalizeArticle()
}

So we are creating functions based on the logic inside. We don't split a function just to split it.

Code repetition

Now I want to talk about code repetition. So in all language duplicating of same code is considered bad practice. But this is the same like with splitting a function just to split it. Try to avoid duplicating just because you saw 5 likes of the code that looks similar in 2 places of your project is not the correct way of writing code. We need to thing about creating isolated shared things that we can use in different places.

const capitalizeTitle = 'some article title'.charAt(0).toLocaleUpperCase() + str.slice(1);

const capitalizeUserName = 'foo'.charAt(0).toLocaleUpperCase() + str.slice(1);

const capitalize = (str) => {
    return str.charAt(0).toLocaleUpperCase() + str.slice(1);
};

So here our code to capitalize a string is really a duplicate which can be moved in a sharable function to capitalize any string. Now we can just call capitalize on any type of data. But just be aware that it's not always necessary. One hint when making something sharable is bad is when you need to write a lot of if condition based on in what case you are. For popular example is that login and register pages are almost similar and you just get 1 more field in register. But actually all labels, api request and other things are different and you end up with writing lots of conditions to make a sharable logic between them.

Stick to coding style

In javascript world we have amazing tool to help us writing better code. Especially for beginners I highly recommend to install eslint which is the most popular linting system and it will show you all basic javascript errors and warning in your code and with time it will help you to improve your code a lot. Also it allows you to stick to one coding style which can be specified in eslint through config. Just pick some popular eslint config and you are good to go.

Don't trust anybody

When you are writing code normally especially at the beginning you write only happy path. So you don't think that your code will do if it gets incorrect data in a function on network error from API. You always want to write you code as safe and unbreakable as possible. Of course it is can be difficult to just change the way how you write code at once but just keep it in mind.

So this were my 10 javascript best practices for beginners. If you will follow them your code quality will increase with time significantly.

Want to conquer your next JavaScript interview? Download my FREE PDF - Pass Your JS Interview with Confidence and start preparing for success today!

📚 Source code of what we've done
Did you like my post? Share it with friends!
Don't miss a thing!
Follow me on Youtube, Twitter or Instagram.
Oleksandr Kocherhin
Oleksandr Kocherhin is a full-stack developer with a passion for learning and sharing knowledge on Monsterlessons Academy and on his YouTube channel. With around 15 years of programming experience and nearly 9 years of teaching, he has a deep understanding of both disciplines. He believes in learning by doing, a philosophy that is reflected in every course he teaches. He loves exploring new web and mobile technologies, and his courses are designed to give students an edge in the fast-moving tech industry.