Code Quality

Long JavaScript Functions: When They Become a Problem

Functions over 30-40 lines typically violate the Single Responsibility Principle. Long functions are harder to read, test, and debug.


❌ Overly Long Route Handler

app.post('/checkout', async (req, res) => {
  const { cartId, paymentMethod, address } = req.body;
  if (!cartId || !paymentMethod) return res.status(400).json({ error: 'Missing fields' });
  const cart = await Cart.findById(cartId);
  if (!cart) return res.status(404).json({ error: 'Cart not found' });
  let total = 0;
  for (const item of cart.items) {
    const product = await Product.findById(item.productId);
    total += product.price * item.quantity;
  }
  const charge = await stripe.charges.create({ amount: total * 100, currency: 'usd' });
  const order  = await Order.create({ cartId, total, charge: charge.id, address });
  res.json({ orderId: order.id });
});

✅ Refactored into Service Functions

app.post('/checkout', async (req, res) => {
  try {
    validateCheckoutInput(req.body);
    const cart   = await loadCart(req.body.cartId);
    const total  = await calculateCartTotal(cart);
    const charge = await processPayment(total, req.body.paymentMethod);
    const order  = await createOrder(cart, total, charge, req.body.address);
    res.json({ orderId: order.id });
  } catch (err) {
    res.status(err.status || 500).json({ error: err.message });
  }
});
💡

Pro tip: Add max-lines-per-function: [warn, 30] to your ESLint config to flag functions as they approach the limit.

Paste this code into LearnCodeGuide

Detect JavaScript vulnerabilities and bugs automatically with AI-powered analysis.

Analyze JavaScript Code →

Related Guides

Javascript Duplicate CodeJavascript Callback HellJavascript Dead Code