SmartCodingTips

๐Ÿš€ JavaScript Performance Tips

Writing efficient JavaScript not only improves user experience but also boosts SEO and reduces CPU usage. Here's a set of practical tips to write faster, leaner code.


๐ŸŽฏ 1. Minimize DOM Access

Accessing and manipulating the DOM is relatively slow. Cache DOM lookups and avoid excessive changes.

// โŒ Bad
document.getElementById("user").style.display = "none";
document.getElementById("user").style.color = "red";

// โœ… Better
const userEl = document.getElementById("user");
userEl.style.display = "none";
userEl.style.color = "red";

๐Ÿ”„ 2. Debounce & Throttle Events

Prevent rapid-fire event handlers (like scroll or resize) from bogging down performance.

// Debounce Example
function debounce(func, delay) {
  let timeout;
  return function () {
    clearTimeout(timeout);
    timeout = setTimeout(func, delay);
  };
}

window.addEventListener("resize", debounce(() => {
  console.log("Window resized!");
}, 300));

๐Ÿงฎ 3. Use Local Variables

Local variables are faster to access than globals or object properties.

// โŒ Slower
for (let i = 0; i < arr.length; i++) {}

// โœ… Faster
const len = arr.length;
for (let i = 0; i < len; i++) {}

๐Ÿงน 4. Remove Unused Code & Variables

Clean, minimal code runs faster and is easier to maintain. Dead code also bloats bundle size.


๐Ÿ“ฆ 5. Minify & Bundle

Use tools like Vite, Webpack, or esbuild to minify and bundle your JS files for production.


๐ŸŒ 6. Load Scripts Efficiently

  • Use defer to delay script execution until DOM is ready.
  • Place scripts at the end of <body> if not using defer.
  • Use async for third-party, non-blocking scripts.
<script src="main.js" defer></script>

๐Ÿง  7. Avoid Memory Leaks

Always clean up timers, intervals, and event listeners to prevent memory bloat.

const interval = setInterval(() => {
  // Do something
}, 1000);

// Clear it when no longer needed
clearInterval(interval);

๐Ÿ“ˆ 8. Profile and Measure

  • Use Chrome DevTools โ†’ Performance Tab
  • Use console.time() and console.timeEnd()
  • Look for slow scripts, reflows, and repaints
console.time("loop");
for (let i = 0; i < 10000; i++) {
  // simulate task
}
console.timeEnd("loop");

โœ… Summary Checklist

  • Minimize DOM access
  • Debounce/throttle expensive events
  • Cache values in loops
  • Clean unused code
  • Use efficient loading strategies
  • Profile and fix performance bottlenecks

Apply these tips to every project for a smoother, faster JavaScript experience!