JavaScript Add Methods

Master classList.add() for DOM manipulation and Atomics.add() for concurrent programming

JavaScript provides two distinct add methods that serve different purposes: classList.add() for DOM manipulation and Atomics.add() for concurrent programming. Understanding both helps you build responsive web interfaces and leverage modern browser capabilities for high-performance web applications.

This guide covers syntax, usage patterns, and practical examples for each method.

Two Ways to Add in JavaScript

classList.add()

Add CSS classes to DOM elements for dynamic styling and UI state management

Atomics.add()

Perform atomic addition operations on shared memory for concurrent programming

Multiple Classes

Add multiple classes in a single call by passing them as separate arguments

Return Values

Atomics.add() returns the old value before addition, useful for implementing counters

DOM classList.add()

The classList.add() method is part of the DOM Element API and provides a clean, reliable way to add CSS classes to HTML elements without overwriting existing classes.

Syntax and Basic Usage

The method accepts one or more class names as arguments and adds them to the element's classList collection. Unlike directly manipulating element.className, classList.add() preserves existing classes, making it the preferred approach for dynamic styling and interactivity.

element.classList.add('className');
element.classList.add('class1', 'class2', 'class3');

Adding Multiple Classes

You can add multiple classes in a single call by passing them as separate arguments. This is more efficient than multiple calls and ensures all classes are added atomically.

const card = document.querySelector('.card');
card.classList.add('featured', 'highlighted', 'premium');

Practical Use Cases

Common applications include:

  • Toggle UI states (active, disabled, expanded)
  • Add animation classes for transitions
  • Apply theme classes (dark mode, compact mode)
  • Mark elements as visited, selected, or interacted
  • Conditional styling based on user actions

For advanced patterns combining class manipulation with asynchronous operations, see our guide on async JavaScript patterns.

classList.add() Examples
1// Example: Toggle active state on button click2const buttons = document.querySelectorAll('.tab-button');3 4buttons.forEach(button => {5 button.addEventListener('click', () => {6 // Remove active class from all buttons7 buttons.forEach(btn => btn.classList.remove('active'));8 // Add active class to clicked button9 button.classList.add('active');10 });11});12 13// Example: Add multiple classes for card state14const card = document.querySelector('.card');15card.classList.add('featured', 'highlighted', 'premium');

Atomics.add()

The Atomics.add() method is part of JavaScript's concurrency features, introduced with SharedArrayBuffer. It performs atomic addition operations on shared memory, guaranteeing that no other thread can interrupt the operation.

Understanding Atomic Operations

In concurrent programming, an atomic operation is one that completes entirely without interruption. When multiple threads access the same memory location simultaneously, race conditions can occur. Atomics.add() ensures that the read-modify-write sequence happens as a single, uninterruptible unit. This pattern is essential for high-performance applications requiring thread coordination.

Syntax and Parameters

Atomics.add(typedArray, index, value)

Parameters:

  • typedArray: An integer typed array (Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, BigUint64Array)
  • index: The position in the array to modify
  • value: The number to add to the current value

Return Value

The method returns the old value at the specified position before the addition. This is useful for implementing counters and locks in concurrent algorithms. For related advanced patterns, explore our coverage of iterators and generators.

Atomics.add() Examples
1// Create a SharedArrayBuffer with shared memory2const buffer = new SharedArrayBuffer(16);3const uint8 = new Uint8Array(buffer);4uint8[0] = 7;5 6// 7 + 2 = 9, Atomics.add returns the old value (7)7const oldValue = Atomics.add(uint8, 0, 2);8console.log('Old value:', oldValue); // Output: 79 10// Verify the new value11console.log('New value:', Atomics.load(uint8, 0)); // Output: 912 13// Practical example: thread-safe counter14const sab = new SharedArrayBuffer(1024);15const ta = new Uint8Array(sab);16 17// Initialize counter18ta[0] = 0;19 20// Add 12 atomically - returns 0 (old value)21Atomics.add(ta, 0, 12);22 23// Current value is now 1224console.log('Counter:', Atomics.load(ta, 0)); // Output: 12

Frequently Asked Questions

What is the difference between classList.add() and className assignment?

classList.add() preserves existing classes and is the safer approach. Assigning to className overwrites all classes, which can break existing styling.

Can classList.add() add multiple classes at once?

Yes, pass multiple class names as separate arguments: element.classList.add('class1', 'class2', 'class3')

What happens if I add a class that already exists with classList.add()?

Nothing - classList.add() only adds classes that don't already exist, making it idempotent.

What browsers support Atomics.add()?

Atomics.add() is supported in modern browsers since late 2021. It requires a secure context (HTTPS) and SharedArrayBuffer support.

When should I use Atomics.add() instead of regular arithmetic?

Use Atomics.add() when multiple threads (web workers) need to modify the same shared memory location to prevent race conditions.

What typed arrays work with Atomics.add()?

All integer typed arrays: Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, and BigUint64Array.

Best Practices

For classList.add():

  • Use for dynamic styling and UI state management
  • Combine with classList.remove() and classList.toggle() for complete control
  • Check classList.contains() before adding to avoid unnecessary operations
  • Use with event listeners for interactive UI components

For Atomics.add():

  • Use only with SharedArrayBuffer and typed arrays
  • Understand the thread safety implications before implementing
  • Consider whether simpler message passing between workers suffices
  • Ensure your application runs in a secure context (HTTPS)

When to Use Each Method

ScenarioMethod
Add CSS classes to elementsclassList.add()
Toggle UI statesclassList.add() + classList.remove()
Thread-safe countersAtomics.add()
Coordinate web workersAtomics.add()
Dynamic stylingclassList.add()
Lock-free data structuresAtomics.add()

Ready to level up your JavaScript skills? Our web development services team can help you build performant, interactive applications.

Sources

  1. MDN Web Docs - Element.classList - Comprehensive documentation on classList property and add() method with examples and browser compatibility
  2. MDN Web Docs - Atomics.add() - Official documentation for Atomics.add() with syntax, parameters, and examples
  3. GeeksforGeeks - JavaScript Atomics add() Method - Practical examples and code samples for Atomics.add

Build Better Web Applications

Master modern JavaScript techniques to create performant, interactive web experiences.