A comprehensive guide to JavaScript - the versatile programming language for web development, covering modern ES6+ features, DOM manipulation, asynchronous programming, and performance optimization.
JavaScript is a high-level, interpreted programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. It enables interactive web pages and is an essential part of web applications, used for both client-side and server-side development.
Modern JavaScript includes many powerful features that improve code readability and functionality:
// Arrow functions
const multiply = (a, b) => a * b;
// Template literals
const greeting = `Hello, ${name}! Today is ${new Date().toLocaleDateString()}`;
// Destructuring assignment
const { red, green, blue } = color;
const [first, second, ...rest] = array;
// Spread operator
const newArray = [...oldArray, newItem];
const newObject = { ...oldObject, newProperty: value };
// Default parameters
function createColor(r = 0, g = 0, b = 0) {
return { red: r, green: g, blue: b };
}
// Classes
class Color {
constructor(r, g, b) {
this.red = r;
this.green = g;
this.blue = b;
}
toHex() {
return `#${this.red.toString(16).padStart(2, '0')}${this.green.toString(16).padStart(2, '0')}${this.blue.toString(16).padStart(2, '0')}`;
}
static fromHex(hex) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return new Color(r, g, b);
}
}// Query selectors
const element = document.querySelector('.color-picker');
const elements = document.querySelectorAll('.color-swatch');
// Element creation and manipulation
const colorDiv = document.createElement('div');
colorDiv.className = 'color-display';
colorDiv.style.backgroundColor = '#ff5733';
colorDiv.textContent = 'Orange Color';
// Event handling
colorDiv.addEventListener('click', (event) => {
const color = event.target.style.backgroundColor;
navigator.clipboard.writeText(color);
});
// Modern event delegation
document.addEventListener('click', (event) => {
if (event.target.matches('.copy-color')) {
const colorValue = event.target.dataset.color;
copyToClipboard(colorValue);
}
});
// Intersection Observer for lazy loading
const imageObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.add('loaded');
imageObserver.unobserve(img);
}
});
});
document.querySelectorAll('img[data-src]').forEach(img => {
imageObserver.observe(img);
});// File API for image processing
class ImageProcessor {
constructor() {
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');
}
async processFile(file) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
this.canvas.width = img.width;
this.canvas.height = img.height;
this.ctx.drawImage(img, 0, 0);
const imageData = this.ctx.getImageData(0, 0, img.width, img.height);
const colors = this.extractColors(imageData);
resolve(colors);
};
img.onerror = reject;
img.src = URL.createObjectURL(file);
});
}
extractColors(imageData) {
const colors = new Map();
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
const hex = `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
colors.set(hex, (colors.get(hex) || 0) + 1);
}
return Array.from(colors.entries())
.sort((a, b) => b[1] - a[1])
.slice(0, 10)
.map(([color, count]) => ({ color, count }));
}
}
// Clipboard API
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
showNotification('Copied to clipboard!');
} catch (err) {
// Fallback for older browsers
const textArea = document.createElement('textarea');
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
showNotification('Copied to clipboard!');
}
}
// Geolocation API
function getLocation() {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error('Geolocation not supported'));
return;
}
navigator.geolocation.getCurrentPosition(resolve, reject);
});
}// Promise-based API calls
class ColorAPI {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
async fetchColor(colorId) {
try {
const response = await fetch(`${this.baseUrl}/colors/${colorId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Failed to fetch color:', error);
throw error;
}
}
async fetchColorPalette(colors) {
const promises = colors.map(colorId => this.fetchColor(colorId));
try {
const results = await Promise.allSettled(promises);
return results
.filter(result => result.status === 'fulfilled')
.map(result => result.value);
} catch (error) {
console.error('Failed to fetch color palette:', error);
return [];
}
}
// Retry mechanism
async fetchWithRetry(url, options = {}, maxRetries = 3) {
for (let i = 0; i <= maxRetries; i++) {
try {
const response = await fetch(url, options);
if (response.ok) return response;
if (i === maxRetries) throw new Error(`Failed after ${maxRetries} retries`);
} catch (error) {
if (i === maxRetries) throw error;
// Exponential backoff
await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
}
}
}
}
// Debouncing and throttling
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// Usage examples
const debouncedSearch = debounce((query) => {
searchColors(query);
}, 300);
const throttledScroll = throttle(() => {
updateScrollPosition();
}, 100);
document.addEventListener('scroll', throttledScroll);// Dynamic imports for code splitting
class ModuleManager {
constructor() {
this.loadedModules = new Map();
}
async loadModule(moduleName) {
if (this.loadedModules.has(moduleName)) {
return this.loadedModules.get(moduleName);
}
try {
let module;
switch (moduleName) {
case 'colorPicker':
module = await import('./modules/colorPicker.js');
break;
case 'imageProcessor':
module = await import('./modules/imageProcessor.js');
break;
case 'chartGenerator':
module = await import('./modules/chartGenerator.js');
break;
default:
throw new Error(`Unknown module: ${moduleName}`);
}
this.loadedModules.set(moduleName, module);
return module;
} catch (error) {
console.error(`Failed to load module ${moduleName}:`, error);
throw error;
}
}
// Preload modules based on user behavior
preloadModule(moduleName) {
if ('requestIdleCallback' in window) {
requestIdleCallback(() => {
this.loadModule(moduleName);
});
} else {
setTimeout(() => {
this.loadModule(moduleName);
}, 100);
}
}
}
// Memory management
class MemoryManager {
constructor() {
this.cache = new Map();
this.maxCacheSize = 100;
}
set(key, value) {
if (this.cache.size >= this.maxCacheSize) {
// Remove oldest entry
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, value);
}
get(key) {
const value = this.cache.get(key);
if (value) {
// Move to end (LRU)
this.cache.delete(key);
this.cache.set(key, value);
}
return value;
}
clear() {
this.cache.clear();
}
}
// Performance monitoring
class PerformanceMonitor {
constructor() {
this.metrics = new Map();
}
startTimer(name) {
this.metrics.set(name, performance.now());
}
endTimer(name) {
const startTime = this.metrics.get(name);
if (startTime) {
const duration = performance.now() - startTime;
console.log(`${name}: ${duration.toFixed(2)}ms`);
this.metrics.delete(name);
return duration;
}
}
measureFunction(fn, name) {
return (...args) => {
this.startTimer(name);
const result = fn.apply(this, args);
this.endTimer(name);
return result;
};
}
measureAsyncFunction(fn, name) {
return async (...args) => {
this.startTimer(name);
const result = await fn.apply(this, args);
this.endTimer(name);
return result;
};
}
}// Custom error classes
class ColorError extends Error {
constructor(message, code) {
super(message);
this.name = 'ColorError';
this.code = code;
}
}
class ValidationError extends ColorError {
constructor(message, field) {
super(message, 'VALIDATION_ERROR');
this.field = field;
}
}
// Error boundary for components
class ErrorBoundary {
constructor(element) {
this.element = element;
this.errorCount = 0;
this.maxErrors = 5;
}
handleError(error, context = '') {
this.errorCount++;
console.error(`Error in ${context}:`, error);
// Send to error reporting service
this.reportError(error, context);
// Show user-friendly message
this.showErrorMessage(error);
// Prevent error cascade
if (this.errorCount > this.maxErrors) {
this.showFatalError();
}
}
reportError(error, context) {
// Integration with error reporting service
if (window.Sentry) {
window.Sentry.captureException(error, {
tags: { context },
extra: {
url: window.location.href,
userAgent: navigator.userAgent
}
});
}
}
showErrorMessage(error) {
const errorDiv = document.createElement('div');
errorDiv.className = 'error-message';
errorDiv.textContent = 'Something went wrong. Please try again.';
this.element.appendChild(errorDiv);
setTimeout(() => {
errorDiv.remove();
}, 5000);
}
showFatalError() {
this.element.innerHTML = `
Application Error
The application has encountered multiple errors. Please refresh the page.
`;
}
}
// Global error handling
window.addEventListener('error', (event) => {
console.error('Global error:', event.error);
// Handle global errors
});
window.addEventListener('unhandledrejection', (event) => {
console.error('Unhandled promise rejection:', event.reason);
// Handle unhandled promise rejections
});// Color utility functions
class ColorUtils {
static hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
static rgbToHex(r, g, b) {
return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
}
static isValidHex(hex) {
return /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hex);
}
}
// Jest tests
describe('ColorUtils', () => {
describe('hexToRgb', () => {
test('converts valid hex to RGB', () => {
expect(ColorUtils.hexToRgb('#ff0000')).toEqual({ r: 255, g: 0, b: 0 });
expect(ColorUtils.hexToRgb('#00ff00')).toEqual({ r: 0, g: 255, b: 0 });
expect(ColorUtils.hexToRgb('#0000ff')).toEqual({ r: 0, g: 0, b: 255 });
});
test('returns null for invalid hex', () => {
expect(ColorUtils.hexToRgb('invalid')).toBeNull();
expect(ColorUtils.hexToRgb('#gggggg')).toBeNull();
});
});
describe('rgbToHex', () => {
test('converts RGB to hex', () => {
expect(ColorUtils.rgbToHex(255, 0, 0)).toBe('#ff0000');
expect(ColorUtils.rgbToHex(0, 255, 0)).toBe('#00ff00');
expect(ColorUtils.rgbToHex(0, 0, 255)).toBe('#0000ff');
});
});
describe('isValidHex', () => {
test('validates hex colors', () => {
expect(ColorUtils.isValidHex('#ff0000')).toBe(true);
expect(ColorUtils.isValidHex('#f00')).toBe(true);
expect(ColorUtils.isValidHex('ff0000')).toBe(false);
expect(ColorUtils.isValidHex('#gggggg')).toBe(false);
});
});
});Explore these comprehensive pillar articles related to JavaScript
Comprehensive guide to triadic color schemes - three colors evenly spaced around the color wheel that create balanced, vibrant, and dynamic visual compositions with mathematical precision and artistic appeal.
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
Discover more about JavaScript and related color theory concepts
Comprehensive guide to triadic color schemes - three colors evenly spaced around the color wheel that create balanced, vibrant, and dynamic visual compositions with mathematical precision and artistic appeal.
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
A comprehensive guide to monochromatic color schemes - sophisticated single-hue harmonies that create unified visual experiences through systematic variations in saturation, lightness, and tonal relationships, essential for elegant design compositions, brand consistency, and advanced color theory applications requiring cohesive aesthetic unity.
A comprehensive guide to split-complementary color schemes - sophisticated three-color harmonies that combine a base color with two colors adjacent to its complement, creating balanced visual contrast with reduced tension compared to direct complementary pairs, essential for refined design compositions, brand identity systems, and advanced color theory applications.
Discover more color terminology and concepts in our comprehensive glossary.
Browse Full Glossary