27.1 C
Pakistan
Saturday, July 27, 2024

7 Poor Styles for JavaScript Writing

Hi there, fans of JavaScript! We are going to discuss the incorrect ways of writing JavaScript today, which is just as important as learning how to write it correctly! Yes, we’ll go over seven typical hazards that could cause you to stumble and give up.

So fasten your seatbelts and get ready for some outrageous illustrations of JavaScript blunders.

Using an abundance of global variables 🌍

Consider the following scenario: you are working on a large project, and rather than staying organized, you choose to scatter global variables everywhere.

Yes, it might work at first, but as your codebase gets larger, these variables will begin to collide, which could result in unforeseen mistakes and difficult-to-find issues.

Encapsulate your code appropriately within functions and modules to prevent contaminating the global scope.

Negative:

// Global variables everywhere!
let user = 'John';
let cartTotal = 0;

function addToCart(itemPrice) {
  cartTotal += itemPrice;
}

function checkout() {
  // Do something with the cartTotal
}

Good:

// Encapsulate in a function to avoid polluting global scope
(function () {
  let user = 'John';
  let cartTotal = 0;

  function addToCart(itemPrice) {
    cartTotal += itemPrice;
  }

  function checkout() {
    // Do something with the cartTotal
  }
})();
  1. Hell on Callbacks 😱

Have you ever noticed callbacks layered inside of each other in blocks that resemble pyramids? Here we have the notorious “callback hell”!

It occurs when you write code that is challenging to read and maintain due to the disorganized handling of asynchronous operations.

To tame this monster, instead, take advantage of current capabilities like async/await or libraries like Promise.

Negative:

function getUserDetails(userId, callback) {
  getUser(userId, function (user) {
    getOrders(user.id, function (orders) {
      getOrderDetails(orders[0].id, function (orderDetails) {
        // And it goes on and on...
      });
    });
  });
}

Good:

async function getUserDetails(userId) {
  try {
    const user = await getUser(userId);
    const orders = await getOrders(user.id);
    const orderDetails = await getOrderDetails(orders[0].id);
    // Much better!
  } catch (error) {
    // Handle errors here
  }
}
  1. Ignoring Mistake Handling 🚨

Ignoring mistakes won’t make them go away; mistakes still happen! Error management gone wrong can have terrible repercussions.

To maintain stable and dependable code, always incorporate appropriate error handling for any activity that may have problems, be it an API call, a file operation, or another kind of operation.

Negative:

function divide(a, b) {
  return a / b;
}

Good:

function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero!');
  }
  return a / b;
}

4. Relying on eval() 🧨

Yes, eval() has a lot of power, but power also comes with responsibility!

When dynamic code is executed using eval(), it can lead to a number of security flaws.

In most circumstances, there are safer and better alternatives, and it can serve as a gateway for injection attacks.

Negative:

function executeCode(code) {
  eval(code);
}

Good:

function executeCode(code) {
  // A safer approach would be using Function constructor
  const myFunction = new Function(code);
  myFunction();
}
  1. Ignoring the Strict Mode 😉

When you used JavaScript to write careless code, do you recall such moments? That is, until now!

Discover the benefits of rigorous mode for yourself. By identifying frequent errors and deterring improper behavior, it assists you in writing more reliable code.

Negative:

function myFunction() {
  x = 10; // Oops, missing 'var', 'let', or 'const'!
  console.log(x);
}

Good:

function myFunction() {
  'use strict';
  let x = 10;
  console.log(x);
}
  1. Forgetting to Format Code 🙈

Have you ever encountered a coding wall that resembles a battlefield? Your code becomes more challenging to read and comprehend when it has poor formatting.

Spend some time properly formatting your code, making consistent use of indentation, and adhering to recognized style standards such as the Google JavaScript Style Guide and the Airbnb JavaScript Style Guide.

Negative:

function myFunction(){console.log('Hello');let x=5;if(x>0){console.log('x is positive');}}

Good:

function myFunction() {
  console.log('Hello');
  let x = 5;
  if (x > 0) {
    console.log('x is positive');
  }
}
  1. Creating a New Wheel 🎡

There is a huge ecosystem of libraries and frameworks for JavaScript that can effectively address common issues.

Avoid trying to write everything from scratch in an attempt to reinvent the wheel.

Use the resources already available to you, take advice from others, and concentrate on finding solutions to the particular problems your project presents.

Negative:

// Implementing your own AJAX request
function ajaxRequest(url, method, data, callback) {
  // ... lots of code ...
}

// Don't do this!

Good:

// Using a well-established library like Axios
axios.get(url)
  .then(function (response) {
    // Handle the response
  })
  .catch(function (error) {
    // Handle errors
  });

Folks, there you have it! We’ve looked at seven examples of poor JavaScript writing.

It is imperative to write readable and well-maintained code if you want your projects to last and succeed.

Steer clear of these hazards, take lessons from your errors, and work to improve as a JavaScript developer every day.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles