10 things should be avoided as a javascript developer

Ruhul Amin
5 min readFeb 8, 2023
unplash

As a JavaScript developer, it is important to keep in mind the best practices and avoid certain common pitfalls in order to write efficient and maintainable code. Here are ten things that you should avoid as a JavaScript developer

1. Overuse of global variables:

Using too many global variables can make it difficult to keep track of the state of your application and can lead to name collisions. Instead, try to use modules and closure to keep your variables within a well-defined scope

// Avoid this
let userName = "John Doe";
let userAge = 30;
let userAddress = "123 Main St.";

// Instead, use modules
const userModule = (() => {
let name = "John Doe";
let age = 30;
let address = "123 Main St.";

return {
getUser: () => ({ name, age, address })
};
})();

// Usage
console.log(userModule.getUser());

In this example, instead of having three global variables, they are all scoped within the userModule closure. This makes the state of the application easier to manage and reduces the risk of name collisions.

2. Blocking the UI thread:

JavaScript is single-threaded, which means that long-running tasks can freeze the user interface. To avoid this, try to use Web Workers or asynchronous functions to run intensive tasks in the background.

// Avoid this
for (let i = 0; i < 1000000000; i++) {
// Do something intensive
}

// Instead, use Web Workers
const worker = new Worker("./worker.js");
worker.postMessage({ data: "Hello, Worker!" });

3. Neglecting cross-browser compatibility:

Not all browsers implement the same features or behave in the same way. Be sure to test your code on multiple browsers and use feature detection or polyfills to ensure compatibility

// Avoid this
const result = new Map().values();

// Instead, use feature detection or polyfills
if (typeof Map.prototype.values === "function") {
const result = new Map().values();
} else {
// Implement polyfill
}

4. Writing complex code:

Simple code is often easier to read, understand, and maintain. Try to write small, focused functions that do one thing well, and use descriptive functions and variable names to make your code self-explanatory

// Avoid this
const complexFunction = (input) => {
let output = input;
for (let i = 0; i < input.length; i++) {
output = output.slice(0, i) + output.slice(i + 1);
}
return output;
};

// Instead, write simple code
const reverseString = (input) => input.split("").reverse().join("");

5. Not using strict mode:

Strict mode is a mode in JavaScript that makes it easier to write secure and reliable code. Enable strict mode by adding “use strict”; at the top of your script or function.

// Avoid this
function doSomething() {
// Not in strict mode
}

// Instead, use strict mode
function doSomething() {
"use strict";
// In strict mode
}

6. Ignoring performance considerations:

performance is important, especially on mobile devices and low-end hardware. Be mindful of the performance implications of your code, and use tools like the browser’s performance profiler to identify and optimize slow code.

// Avoid this
const slowFunction = (input) => {
let result = 0;
for (let i = 0; i < input.length; i++) {
result += input[i];
}
return result;
};

// Instead, consider performance
const fastFunction = (input) => input.reduce((a, b) => a + b, 0);

7. Not handling errors:

Failing to handle errors can lead to unexpected behavior and make it difficult to diagnose and fix problems. Use try-catch blocks and throw meaningful error messages to handle errors and make debugging easier.

// Avoid this
const unreliableFunction = (input) => {
return input.split("/");
};

// Instead, handle errors
const reliableFunction = (input) => {
try {
return input.split("/");
} catch (error) {
throw new Error(`Cannot split string: ${error.message}`);
}
};

8. Not keeping up with best practices and new features:

Not keeping up with best practices and new features: The JavaScript language and its ecosystem are constantly evolving. Stay up-to-date with the latest best practices and new features by reading blogs and following industry leaders.

// Avoid this
const oldWay = (input) => {
let result = 0;
for (let i = 0; i < input.length; i++) {
result += input[i];
}
return result;
};

// Instead, use new features
const newWay = (input) => input.reduce((a, b) => a + b, 0);

9. Overusing this keyword:

The value of this in JavaScript can be confusing, especially in complex code. Try to use arrow functions, bind, call, and apply to explicitly set the value of this, or use functional programming techniques to avoid it altogether.

// Avoid this
const user = {
name: "John Doe",
age: 30,
address: "123 Main St.",
getUserInfo: function() {
console.log(`Name: ${this.name}`);
console.log(`Age: ${this.age}`);
console.log(`Address: ${this.address}`);
}
};

// Instead, use destructuring
const user = {
name: "John Doe",
age: 30,
address: "123 Main St."
};

const getUserInfo = ({ name, age, address }) => {
console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
console.log(`Address: ${address}`);
};

// Usage
getUserInfo(user);

10. Writing spaghetti code:

Spaghetti code is code that is hard to follow, understand, and maintain. Write clean and well-organized code, and use comments, indentation, and whitespace to make your code readable and understandable.

// Avoid this
function fetchData() {
let data = null;
makeApiCall().then(res => {
data = res;
if (data.status === 200) {
// do something with the data
} else {
// handle error
}
});
}

// Instead, use a clean and modular approach
async function fetchData() {
try {
const res = await makeApiCall();
if (res.status !== 200) {
throw new Error("Failed to fetch data");
}
// do something with the data
} catch (error) {
// handle error
}
}

Resources :

Here’s a list of resources for learning best practices in JavaScript:

  1. MDN Web Docs — JavaScript Guide: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
  2. JavaScript: The Good Parts by Douglas Crockford: https://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742
  3. Clean Code: A Handbook of Agile Software Craftsmanship by Robert Martin: https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882
  4. AirBnB JavaScript Style Guide: https://github.com/airbnb/javascript
  5. Eloquent JavaScript by Marijn Haverbeke: https://eloquentjavascript.net/
  6. JavaScript Design Patterns by Addy Osmani: https://addyosmani.com/resources/essentialjsdesignpatterns/book/
  7. The JavaScript Handbook by Flavio Copes: https://flaviocopes.com/javascript-handbook/
  8. JavaScript Fundamentals by Udemy: https://www.udemy.com/course/javascript-fundamentals/
  9. YouTube: Traversy Media (JavaScript tutorials): https://www.youtube.com/channel/UC29ju8bIPH5as8OGnQzwJyA
  10. Codecademy: Learn JavaScript: https://www.codecademy.com/learn/introduction-to-javascript

👋 Let’s be friends! connect with me on LinkedIn. Don’t forget to follow me here on Medium, and Fiverr as well.

--

--