Skip to content
Learni
View all tutorials
Tests et Expérimentation

How to Implement A/B Testing in JavaScript in 2026

Lire en français

Introduction

A/B tests let you compare two versions of a page to see which one converts better. In 2026 they remain essential for any web optimization strategy. This tutorial shows you how to build a simple yet complete A/B system in vanilla JavaScript with no external libraries. You will create random visitor assignment, display variants, and measure conversions. Every step includes ready-to-use code.

Prerequisites

  • Basic knowledge of HTML, CSS and JavaScript
  • A modern browser
  • A code editor (VS Code recommended)
  • Optional: a Google Analytics account for real tracking

Basic HTML Structure

index.html
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>Test A/B - Bouton CTA</title>
</head>
<body>
  <h1>Bienvenue sur notre site</h1>
  <button id="cta-button">S'inscrire</button>
  <script src="ab-test.js"></script>
</body>
</html>

This basic HTML file contains a button whose text and color will change depending on version A or B. It loads the JavaScript file that handles all test logic.

A/B Assignment Logic

ab-test.js
const variants = {
  A: { buttonText: "S'inscrire maintenant", buttonColor: "#007bff" },
  B: { buttonText: "Rejoindre gratuitement", buttonColor: "#28a745" }
};

function getVariant() {
  const stored = localStorage.getItem('abVariant');
  if (stored) return stored;
  const variant = Math.random() < 0.5 ? 'A' : 'B';
  localStorage.setItem('abVariant', variant);
  return variant;
}

const currentVariant = getVariant();
const config = variants[currentVariant];
const button = document.getElementById('cta-button');
button.textContent = config.buttonText;
button.style.backgroundColor = config.buttonColor;

This script randomly assigns each visitor to variant A or B and stores the choice in localStorage for a consistent experience. It then applies the corresponding visual changes.

Adding Conversion Tracking

ab-test.js
button.addEventListener('click', () => {
  console.log(`Conversion enregistrée pour la variante ${currentVariant}`);
  // En production : envoyer à Google Analytics ou votre backend
  // gtag('event', 'conversion', { variant: currentVariant });
  alert('Merci ! Votre conversion a été enregistrée.');
});

The click listener records the conversion. In production, replace console.log with a call to your analytics tool to accurately measure which variant performs best.

Extended Variants with CSS

styles.css
.variant-A { background-color: #007bff; }
.variant-B { background-color: #28a745; }
#cta-button { padding: 12px 24px; font-size: 18px; color: white; border: none; border-radius: 4px; cursor: pointer; }

Add these styles to make the variants visually distinct. Apply the classes dynamically in the JavaScript according to the chosen variant.

Complete Final Script

ab-test-complete.js
const variants = {
  A: { buttonText: "S'inscrire maintenant", buttonColor: "#007bff", class: "variant-A" },
  B: { buttonText: "Rejoindre gratuitement", buttonColor: "#28a745", class: "variant-B" }
};

function getVariant() {
  const stored = localStorage.getItem('abVariant');
  if (stored) return stored;
  const variant = Math.random() < 0.5 ? 'A' : 'B';
  localStorage.setItem('abVariant', variant);
  return variant;
}

const currentVariant = getVariant();
const config = variants[currentVariant];
const button = document.getElementById('cta-button');
button.textContent = config.buttonText;
button.style.backgroundColor = config.buttonColor;
button.classList.add(config.class);
button.addEventListener('click', () => {
  console.log(`Conversion variante ${currentVariant}`);
  alert('Conversion enregistrée !');
});

This file combines all logic: assignment, variant application, and tracking. Copy and paste it directly to get a working A/B test.

Best Practices

  • Always store the variant in localStorage to prevent version changes during the session
  • Use a 50/50 split for statistically reliable results
  • Clearly define the conversion goal before launching the test
  • Run the test for a sufficient period (minimum 1-2 weeks)
  • Document each variant and its hypotheses

Common Mistakes to Avoid

  • Forgetting to persist the variant (changes on every reload)
  • Not segmenting results by traffic source
  • Running multiple tests simultaneously on the same page
  • Ignoring statistical significance of results

Going Further

Deepen your optimization skills with our Learni training courses dedicated to advanced A/B testing and product experimentation.