DEV Community

Cover image for Bad Practices In JavaScript
Kamran Ahmad
Kamran Ahmad

Posted on

Bad Practices In JavaScript

Certainly, here are some common bad practices in JavaScript that you should avoid to write clean, maintainable, and efficient code:

  1. Using Global Variables: Relying heavily on global variables can lead to naming conflicts, unintended data modification, and difficulty in debugging and maintaining code.
// Global variable
var globalCounter = 0;

function incrementCounter() {
    globalCounter++;
    console.log(globalCounter);
}

// Avoid global variables
function incrementCounter(counter) {
    counter++;
    console.log(counter);
    return counter;
}

let localCounter = 0;
localCounter = incrementCounter(localCounter);


Enter fullscreen mode Exit fullscreen mode
  1. Not Using Proper Variable Declaration: Always declare variables with var, let, or const to avoid polluting the global scope and to ensure proper scoping.
//Bad Practice: Using var instead of const/let
var count = 0;


//Better Practice
let count = 0; // Use let or const based on reassignment
const MAX_COUNT = 10; // Use const for constants

Enter fullscreen mode Exit fullscreen mode
  1. Not Handling Errors: Failing to handle errors can lead to unexpected crashes or issues in your application. Always use try-catch blocks or promises to handle potential errors gracefully.
// Not handling errors
try {
    // Code that might throw an error
} catch (error) {
    // No error handling
}

// Handling errors
try {
    // Code that might throw an error
} catch (error) {
    console.error("An error occurred:", error);
}


Enter fullscreen mode Exit fullscreen mode
  1. Callback Hell: Nesting callbacks excessively (also known as callback hell) can make code difficult to read and maintain. Consider using promises, async/await, or libraries like async.js to manage asynchronous operations more elegantly.
asyncFunction1(() => {
    asyncFunction2(() => {
        asyncFunction3(() => {
            // More nested callbacks
        });
    });
});

//Better Practice

asyncFunction1()
    .then(() => asyncFunction2())
    .then(() => asyncFunction3())
    .then(() => {
        // Code after all async operations
    })
    .catch((error) => {
        console.error("An error occurred:", error);
    });

Enter fullscreen mode Exit fullscreen mode
  1. Not Using "strict" Mode: Not using strict mode can lead to subtle bugs. Enable strict mode by adding "use strict"; at the beginning of your script or function.

6.Ignoring Semicolons: While JavaScript allows optional semicolons, it's a good practice to include them. Omitting semicolons can lead to unexpected behavior due to automatic semicolon insertion

const message = "Hello"
console.log(message)

//Better Practice
const message = "Hello";
console.log(message);

Enter fullscreen mode Exit fullscreen mode

7.Using == Instead of ===: Always use strict equality (===) instead of loose equality (==) to avoid type coercion and unexpected comparison results.

if (value == 10) {
    // This could lead to unexpected type coercion
}


if (value === 10) {
    // Use strict equality to avoid type coercion
}


Enter fullscreen mode Exit fullscreen mode

Top comments (24)

Collapse
 
sloan profile image
Sloan the DEV Moderator

Hey, this article seems like it may have been generated with the assistance of ChatGPT.

We allow our community members to use AI assistance when writing articles as long as they abide by our guidelines. Could you review the guidelines and edit your post to add a disclaimer?

Collapse
 
florianrappl profile image
Florian Rappl

The use strict tip is actually bad practice. The strict mode should not clutter your code - this is something that either the build tooling (e.g., webpack, vite, ...) adds to your bundle or that your file has implicitly (you should use ESM - and these are strict by default).

Collapse
 
shnew profile image
Sh

did you just copy paste from chat gpt?

Collapse
 
ikamran01 profile image
Kamran Ahmad • Edited

yes, some of the snippet but before you copy from that you have go through of code of conduct of dev to

Collapse
 
shnew profile image
Sh

It's ok to use gpt but like someone says it's mediocre content, I'd you're using gpt atleast make advance stuff that's worth so many peoples time... hope to see good work from you

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Type coercion is often extremely useful. I will never understand why developers are not keen to embrace some parts of JS. Use == or === as appropriate, don't always favour one over the other.

Collapse
 
tracygjg profile image
Tracy Gilmore

Hi Jon,
Would you also agree there are times (although few) when var is a more appropriate declaration mechanism than const or let?
I think many of the points given above are valid but it can be less than helpful to have blanket statements such as 'x is bad, y is good'.
There are exceptions to every rule.

Collapse
 
dagnelies profile image
Arnaud Dagnelies

When would var be better? ... I never missed it, so I wonder.

Thread Thread
 
tracygjg profile image
Tracy Gilmore

Consider the case when a variable is initialised (not declared) in one scope and used in another. In order to achieve this with let the variable has to be declared outside of both scopes and this means it will exist in the Temporal Dead Zone (TDZ) until it gets initialised. This can be avoided by using var to declare the variable at the point of initialisation. Because the variable will have 'function scope' it will still be accessible in the subsequent scope. Here is a very contrived example and I accept this might not be the best justification.
The let and const keywords have their use but they are not complete replacements for var, only more appropriate in some case, just like == and conventional functions.

Collapse
 
bossoff profile image
Raji Samad

Point

Collapse
 
ipazooki profile image
Mo • Edited

I appreciate your work! These are very useful suggestions.

I wonder, what are the benefits of using promises, async/await, or libraries like async.js over nested callbacks? I mean apart from coding style. Is there any performance benefit too?

Collapse
 
ikamran01 profile image
Kamran Ahmad

I'm glad you find the information helpful! Moving from nested callbacks to using constructs like Promises, async/await, and libraries like async.js offers several benefits beyond just improving code readability and style. While the primary advantages might not always be related to performance, there can be some performance benefits as well.

Collapse
 
ikamran01 profile image
Kamran Ahmad
Collapse
 
agordon123 profile image
Adam Gordon • Edited

Can I just point out that this is exactly what comes out when you ask chat gpt the question? Right down to the certainly, I use ChatGPT enough to get the feeling that this is what comes out when you propose the question to it.

Rather than make this personal, does this not seem ethically questionable to anyone? Are ChatGPT wrriten articles something we should be encouraging, or at least acknowledging? Can I become a writer with a following by thinking up questions, asking ChatGPT, and C/P it and pass it off as my own and people would be fine with that?

This isn't about the person who wrote the article nor any of the points, this is about the very quick effects of having a service that produces cookie cutter revenue for people without requiring a disclosure or even anyone else questioning it, and if the poster did happen to write this themselves, then sorry I apolgize for the implication. But this is one of the big ethical questions of how accepting we should be of AI, and why it's important we tackle this now before its too late and we're all ChatGPT.

Collapse
 
ikamran01 profile image
Kamran Ahmad

ok bro understand your but if anyone has lack of time and and writting have to publish that,
one thing that why devloper use stackoverflow to copy past thare may snappit website are buit to make work easy and take less time why ? why evey one follow chatgpt most of the time and why it still going why pepople use it to for genrating content why its not stope since it started

bro keep your hate aside and i am giving this tip to make pepole aware what is that proble in this ??

hate is easey but support is not prety easy to get .

and you everywhere criticise me use that gentation snappit yes i use becous i didn't have to write that

ok i love your hate bro

nice to meet you

Collapse
 
agordon123 profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Adam Gordon • Edited

Point was made, reputation is everything when it comes to technical writing and professional expertise. The world isn't always fair but it's on every individual around the globe to maintain some sense of ethical standards. With all the division and mistrust in the world, it's imperative now more than ever to try to take the high road when possible.

Collapse
 
clickit_devops profile image
ClickIT - DevOps and Software Development

Great post, thank you. It's important to have this type of guides to be aware of the practices that may be affecting our process and results.

Collapse
 
ikamran01 profile image
Kamran Ahmad

most welcome dear stay connected for such type post and guides

Collapse
 
agordon123 profile image
Adam Gordon

the guy just asks ChatGPT a question and copy and pastes it. I spotted it and made it as impersonal as possible and as you can see, my post has been taken down by the author. Don't know what your actual business is, or if theres some connection or something, but the hypocrisy with people saying not to worry about AI replacing people, using AI to replace other people's knowledge without the work ethic to even make it look good, that happens to be one of my trigger points.

If you're in on the game, shame on ya, if you're independent and were makin an honest comment, I'd cut ties with this guy, he made it personal with me and I'd hate to have to do reputational harm to someone who didnt deserve it.

I say this not to you really, but anyone who is boosting this guy, they've made an enemy with alot of time on their hands and enough of a moral compass to not be a total hypocrite (not saying im a perfect person but I understand right from wrong and can attest to the consciousness of guilt of this dude, who's going to be the reason that AI becomes just another terrible addition to the zeitgest),

Collapse
 
jd2r profile image
DR

Excellent post! Hit some of the most crucial language practices that people need to know about when working with JS.

Collapse
 
ikamran01 profile image
Kamran Ahmad

that really great to know than you

Collapse
 
ikamran01 profile image
Kamran Ahmad

hey all of you can connet with me via twitter Twitter we will have sapace there get to learn more

thanks all

Collapse
 
pablocubo profile image
Pablo Lara Roloff

Thank you Kamran Ahmad!

It was very helpfull!

Pablo

Collapse
 
ikamran01 profile image
Kamran Ahmad

most welcome and feel great to know this

Some comments may only be visible to logged-in visitors. Sign in to view all comments.