DEV Community

Cover image for Optimise your code with these 5 JavaScript best practices 🚀đŸ”Ĩ
Arjun Vijay Prakash
Arjun Vijay Prakash

Posted on

Optimise your code with these 5 JavaScript best practices 🚀đŸ”Ĩ

1. Naming variables and functions

First, we have the naming convention for variables, functions, and other code structures. This guideline is not only about appearance or meaning, but it also greatly impacts code readability and effective debugging.

In JavaScript, it is recommended to use camel-case for variables and functions (e.g., myVariableName) and Pascal case for classes (e.g., MyClassName).

// ❌ Poorly named variables:
let a = 'John';
let fn = () => console.log('Hello');

// ✅ Descriptive variable names:
let firstName = 'John';
let sayHello = () => console.log('Hello');
Enter fullscreen mode Exit fullscreen mode

2. Use Shorthands but Be Cautious

While shorthand techniques offer a quicker and neater way to write code, it's important to be cautious as they can yield unexpected results. To avoid such unforeseen outcomes, it is essential to consult the documentation, explore relevant JavaScript code examples, and thoroughly test the output.

// ❌ Traditional function declaration:
function square1 (num) {
  return num * num
}
// ✅ Using arrow functions (shorthand):
const square2 = num => num * num

// ❌ Very long code:
let x

if (y) {
  x = y
} else {
  x = 'default'
}

// ✅ A more succinct way to achieve the same result using logical OR:
let x = y || 'default'
Enter fullscreen mode Exit fullscreen mode

3. Follow the SoC principle

For simplicity and organization, it is advisable to avoid using JavaScript for directly applying styling. This principle, known as separation of concerns (SoC), suggests utilizing the classList API to add or remove classes, while defining style rules with CSS.

By following this approach, CSS takes care of styling tasks, while JavaScript focuses on handling other functionalities within your application.

It's important to note that the concept of separation of concerns (SoC) extends beyond JavaScript and serves as a practice to separate functionalities and prevent the mixing of different technologies.

In summary, CSS should handle CSS-related tasks, while JavaScript should refrain from dealing with styling concerns.

// ❌ Avoid using JavaScript for styling:
let element = document.getElementById('my-element')
element.style.color = 'red'

// ✅ Changing styles by adding/removing classes:
let element = document.getElementById('my-element')
element.classList.add('my-class')
Enter fullscreen mode Exit fullscreen mode

4. Understand the Lack of Hoisting in Classes

In contrast to functions, classes in JavaScript do not undergo hoisting, which implies that you must declare a class before invoking it. Initially, this might appear counterintuitive, especially if you're familiar with function hoisting. However, it is an essential principle that should be comprehended and followed when working with classes in JavaScript.

// ❌ Calling a class before declaration:
const hat = new Hat('Red', 1000)
hat.show()
class Hat {
  constructor (color, price) {
    this.color = color
    this.price = price
  }
  show () {
    console.log(`This ${this.color} hat costs $${this.price}`)
  }
}

// ✅ Calling a class after declaration:
class Hat {
  constructor (color, price) {
    this.color = color
    this.price = price
  }
  show () {
    console.log(`This ${this.color} hat costs $${this.price}`)
  }
}

const hat = new Hat('Red', 1000)
Enter fullscreen mode Exit fullscreen mode

5. Avoid the Over-Nesting in your code

One of the most prevalent errors made by beginners is excessive nesting of blocks, where they place a block within another block, such as a for loop inside another loop inside an if-else statement within a try-catch block, and so on.

As a result, the code becomes cluttered, making it challenging to understand its functionality or locate the specific code responsible for a particular task. Debugging such code can be overwhelming and difficult, and it may also confuse other programmers who come across it. Additionally, this practice can convey an unprofessional impression.

To mitigate these issues, it is crucial to avoid excessive nesting and strive for cleaner, more organized code structure.

// ❌ Nesting code blocks too much and not using the return keyword
function checkNumber (num) {
  if (num > 0) {
    console.log('Number is positive.')
  } else {
    if (num < 0) {
      console.log('Number is negative.')
    } else {
      console.log('Number is zero.')
    }
  }
}

// ✅ Using the return keyword instead of the else statement
function checkNumber (num) {
  if (num > 0) {
    console.log('Number is positive.')
    return
  }

  if (num < 0) {
    console.log('Number is negative.')
    return
  }

  console.log('Number is zero.')
}
Enter fullscreen mode Exit fullscreen mode

I have always been deeply passionate about writing, and nothing brings me more joy than offering assistance and inspiration to others. If you have any inquiries or require any guidance, please don't hesitate to contact me. I am here to help!

My Instagram - @arjuncoder
My Github - @CoderPOOP
My Twitter - @arjuncodess

Top comments (3)

Collapse
 
devangtomar profile image
Devang Tomar

Well written! 👍

Collapse
 
codecraftjs profile image
Code Craft-Fun with Javascript

Very Informative!
To avoid bad practices in code, its important to understand the core working of language. With this, you widen your vision of imagination while writing a code.
I try to explain important Javascript concepts in a simpler way through my blogs.

Collapse
 
lico profile image
SeongKuk Han

Awesome. Good tips!
I'd like to know more about the first and the second such as good cases and bad cases of naming and shorthands.