Code Optimization
Learn advanced code optimization techniques for production JavaScript applications
75 minโขBy Priygop TeamโขLast updated: Feb 2026
Performance Optimization
Optimize JavaScript code for better performance, smaller bundle sizes, and faster execution.
Bundle Optimization
Example
// webpack.config.js - Bundle optimization
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\/]node_modules[\/]/,
name: 'vendors',
chunks: 'all'
}
}
},
usedExports: true,
sideEffects: false
},
plugins: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
}
})
]
};Tree Shaking
Example
// ES6 modules for tree shaking
// utils.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
export const divide = (a, b) => a / b;
// main.js
import { add } from './utils.js';
// Only 'add' function will be included in bundle
// CommonJS (not tree-shakeable)
const utils = require('./utils');
// Entire utils module will be includedLazy Loading
Example
// Dynamic imports for lazy loading
const loadModule = async () => {
const module = await import('./heavy-module.js');
return module.default;
};
// React lazy loading
const LazyComponent = React.lazy(() => import('./HeavyComponent'));
// Route-based code splitting
const routes = [
{
path: '/',
component: () => import('./pages/Home')
},
{
path: '/about',
component: () => import('./pages/About')
}
];Memory Optimization
Example
// Memory leak prevention
class DataProcessor {
constructor() {
this.cache = new Map();
this.cleanupInterval = setInterval(() => {
this.cleanupCache();
}, 60000); // Clean every minute
}
processData(data) {
const key = JSON.stringify(data);
if (this.cache.has(key)) {
return this.cache.get(key);
}
const result = this.expensiveOperation(data);
this.cache.set(key, result);
return result;
}
cleanupCache() {
// Remove old entries
const now = Date.now();
for (const [key, value] of this.cache) {
if (now - value.timestamp > 300000) { // 5 minutes
this.cache.delete(key);
}
}
}
destroy() {
clearInterval(this.cleanupInterval);
this.cache.clear();
}
}Mini-Project: Performance Optimizer
Example
// Performance optimization utility
class PerformanceOptimizer {
static debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
static throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
static memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
static imageOptimizer() {
return {
lazyLoad: (img) => {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const image = entry.target;
image.src = image.dataset.src;
observer.unobserve(image);
}
});
});
observer.observe(img);
},
compress: (file, quality = 0.8) => {
return new Promise((resolve) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
canvas.toBlob(resolve, 'image/jpeg', quality);
};
img.src = URL.createObjectURL(file);
});
}
};
}
}