JavaScript APIs & Web Standards

Modern JavaScript & Web APIs

ECMAScript Standards

JavaScript follows the ECMAScript specification (ES2015+) and integrates with numerous Web APIs to provide rich, interactive experiences while maintaining accessibility and performance.

ES2015+ Features
  • Arrow functions: Concise function syntax
  • Template literals: String interpolation with backticks
  • Destructuring: Extract values from objects/arrays
  • Modules: import/export for code organization
  • Promises & async/await: Asynchronous programming
  • Classes: Object-oriented programming syntax
Accessible JavaScript
  • Keyboard navigation: Support Tab, Enter, Escape, Arrow keys
  • ARIA updates: Manage aria-expanded, aria-live regions
  • Focus management: Proper focus on dynamic content
  • Progressive enhancement: Work without JavaScript
  • Screen reader support: Announce dynamic changes

DOM Manipulation & Event Handling

Modern DOM APIs

Element Selection & Manipulation
// Modern element selection
const button = document.querySelector('#submit-btn');
const cards = document.querySelectorAll('.card');

// Element manipulation
button.classList.add('active');
button.setAttribute('aria-expanded', 'true');
button.textContent = 'Loading...';

// Modern insertion methods
const newElement = document.createElement('div');
newElement.textContent = 'New content';
container.append(newElement); // or prepend, before, after

// Event handling with modern syntax
button.addEventListener('click', async (event) => {
  event.preventDefault();
  
  // Update ARIA state
  button.setAttribute('aria-busy', 'true');
  
  try {
    const result = await fetchData();
    updateUI(result);
  } catch (error) {
    showError(error.message);
  } finally {
    button.setAttribute('aria-busy', 'false');
  }
});
Best Practices
  • Use semantic events: click, submit, change
  • Event delegation: Handle events on parent elements
  • Remove listeners: Prevent memory leaks
  • Passive listeners: Improve scroll performance
  • Error handling: Graceful fallbacks

Fetch API & Asynchronous Operations

Fetch API Best Practices
// Modern fetch with error handling
async function fetchData(url) {
  try {
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      // Signal for request cancellation
      signal: AbortSignal.timeout(5000)
    });
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Request timed out');
    }
    throw error;
  }
}
Security Considerations
  • CSRF protection: Include anti-CSRF tokens
  • Content validation: Validate response content type
  • Timeout handling: Set reasonable request timeouts
  • Error disclosure: Don't expose sensitive errors
  • CORS policy: Proper cross-origin configuration
  • Input sanitization: Sanitize all user inputs

Web Storage & Offline APIs

Local Storage

Persistent storage for simple key-value data across browser sessions

// Store data
localStorage.setItem('user', JSON.stringify(userData));

// Retrieve data
const user = JSON.parse(localStorage.getItem('user') || '{}');
Session Storage

Temporary storage that persists only for the browser tab session

// Store temporary data
sessionStorage.setItem('formData', JSON.stringify(form));

// Auto-clear on tab close
IndexedDB

Large-scale structured data storage with transactions and indexes

// Advanced client-side database
const request = indexedDB.open('MyDB', 1);
// Complex queries and transactions

Device Integration APIs

Geolocation API

Access user's location with proper permission handling:

// Request location with options
navigator.geolocation.getCurrentPosition(
  (position) => {
    const { latitude, longitude } = position.coords;
    console.log(`Location: ${latitude}, ${longitude}`);
  },
  (error) => {
    console.error('Location error:', error.message);
  },
  {
    enableHighAccuracy: true,
    timeout: 10000,
    maximumAge: 300000
  }
);

Always request permission gracefully and provide fallbacks.

Notification API

Send notifications with user permission:

// Request notification permission
if ('Notification' in window) {
  const permission = await Notification.requestPermission();
  
  if (permission === 'granted') {
    new Notification('Hello!', {
      body: 'This is a notification',
      icon: '/icon.png',
      tag: 'unique-notification'
    });
  }
}

Respect user preferences and don't spam notifications.

Performance & Monitoring APIs

Performance Monitoring

Use JavaScript performance APIs to monitor and improve web application performance.

Performance API
// Measure performance
const start = performance.now();

// Your code here
doSomeWork();

const end = performance.now();
console.log(`Operation took ${end - start} milliseconds`);

// Core Web Vitals
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.entryType === 'navigation') {
      console.log('Page load time:', entry.loadEventEnd - entry.fetchStart);
    }
  }
});

observer.observe({ entryTypes: ['navigation', 'paint'] });
Intersection Observer
// Lazy loading images
const imageObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src;
      img.classList.remove('lazy');
      imageObserver.unobserve(img);
    }
  });
});

// Observe lazy images
document.querySelectorAll('img[data-src]').forEach(img => {
  imageObserver.observe(img);
});

Progressive Web App APIs

Service Workers

Background scripts for offline functionality, push notifications, and caching strategies

Cache API

Programmatic cache management for offline-first applications and performance optimization

Web App Manifest

Define app metadata for installation and native-like experience on mobile devices

Error Handling & Debugging

Robust Error Handling

Error Handling Strategies
// Global error handling
window.addEventListener('error', (event) => {
  console.error('Script error:', event.error);
  // Send to error reporting service
  reportError({
    message: event.message,
    source: event.filename,
    line: event.lineno,
    column: event.colno,
    error: event.error
  });
});

// Promise rejection handling
window.addEventListener('unhandledrejection', (event) => {
  console.error('Unhandled promise rejection:', event.reason);
  event.preventDefault(); // Prevent console error
});

// Try-catch with proper error handling
async function safeAsyncOperation() {
  try {
    const result = await riskyOperation();
    return result;
  } catch (error) {
    // Log error for debugging
    console.error('Operation failed:', error);
    
    // Show user-friendly message
    showNotification('Something went wrong. Please try again.', 'error');
    
    // Return safe fallback
    return getDefaultValue();
  }
}
Security Best Practices
  • Input validation: Validate all user inputs
  • XSS prevention: Use textContent, not innerHTML
  • CSRF tokens: Include in API requests
  • Content Security Policy: Restrict script execution
  • Secure cookies: HttpOnly, Secure, SameSite
  • Subresource integrity: Verify external scripts
JavaScript Standards Checklist
Modern JavaScript
Accessibility & Performance

Advance JavaScript Standards

Report JavaScript compatibility issues and access resources for modern web development.