Learn by example

JavaScript Snippets for Beginners

JavaScript makes web pages respond to people. It can update text, validate input, switch themes, fetch data, store preferences, and react to clicks. The best way to learn it is to read a small example, predict what it will do, run it, and then change one part at a time.

What you will learn

Begin with variables, strings, arrays, conditions, functions, and event listeners. Prefer clear names and small functions. Use textContent for plain text, handle errors around network requests, and give visitors feedback when an action succeeds or fails. Client-side JavaScript improves the interface, but it cannot replace server-side checks for sensitive operations.

Understand the event-driven model

A browser waits for events such as clicks, input changes, form submissions, and page loading. addEventListener connects an event to a function. This approach keeps behavior close to the user action that triggers it. Avoid attaching the same handler repeatedly when a component is initialized more than once, and make sure selectors match elements that actually exist.

Work with values and the DOM

Variables hold values, arrays group values, and functions let you reuse a sequence of steps. querySelector finds an element using a CSS selector. textContent is a safe default for inserting plain text because it does not interpret the value as HTML markup. When creating list items, create an element and assign its text rather than concatenating untrusted input into innerHTML.

Handle forms and errors clearly

A browser can check required fields and input formats, but users still need clear messages when a submission cannot continue. Listen for the submit event when you need custom behavior and call preventDefault only when you intend to handle the submission yourself. Validate on the server too whenever data leaves the browser, because client-side checks can be bypassed.

Use timers, storage, and network requests carefully

Timers are useful for clocks and countdowns, but they should be stopped when no longer needed. localStorage can save simple preferences on the current browser, yet it is not a secure vault and should not store passwords or secrets. Fetch requests can fail due to connectivity, server errors, or cross-origin restrictions, so show a loading state and handle unsuccessful responses.

Debug with a repeatable process

Read the first useful error in the console, check the line number, and inspect the value that caused the issue. Test the normal path and an error path. Change only one thing at a time, then reload and repeat the test. Small, deliberate experiments teach more than pasting a large script without understanding its flow.

A practical way to learn from a snippet

Read the goal, inspect the markup, and identify which part provides structure, appearance, or behavior. Run the example before editing it. Then make a small change: rename a heading, change a color, add another item, or alter a condition. Predict the result first and compare your prediction with what the browser shows. This habit develops understanding rather than dependence on copy-and-paste.

Copying code responsibly

Examples are starting points, not complete production systems. Replace placeholder names, links, sample data, and image paths before publishing a project. Check licenses and permissions before reusing third-party assets. Never paste API keys, passwords, private tokens, or personal information into a public code example. Review the full snippet before using it, and remove code that does not serve the purpose of your page.

Accessibility is part of good development

Build for keyboard use as well as pointer input. Give form fields labels, use descriptive link text, keep focus indicators visible, and structure content with meaningful headings. Test zoom and narrow screens. If an interactive element changes state, make that state clear to people using assistive technology. Accessibility is not a final decoration; it is part of whether the interface works for real visitors.

From example to complete project

Once a snippet works, move it into a project with a clear file structure. Keep HTML, CSS, and JavaScript organized, use descriptive file names, and remove unused code. Test the result in more than one modern browser when possible. For a live website, check loading speed, broken links, mobile layout, and error messages. Document unusual behavior so future changes are easier.

A short JavaScript checklist

Check that event listeners are attached once, selectors find the intended elements, and the user receives feedback for success and failure. Handle rejected network requests, avoid placing untrusted text into HTML, and do not treat browser storage as secure. Test empty input, unexpected input, and repeated clicks rather than testing only the ideal path.

Common beginner mistakes

Frequent problems include misspelled selectors, confusing a value with a string, forgetting to return a value, and using a variable before it exists. Asynchronous functions also need error handling. When a feature does not work, read the console message and inspect the actual value instead of guessing. Avoid copying code that asks for secrets or performs an action you do not understand.

How to practise with these examples

Run a snippet and predict the result before clicking. Rename variables, add a second button, change an array, or add a message for an empty state. Then break one part intentionally and use the console to identify the issue. This process helps you understand the sequence of events and build confidence debugging your own projects.

Copy and practise

JavaScript Snippets library

Search these examples by name or topic. Open Edit code and practise to change the example and its CSS. Run edited preview to see your changes in a sandboxed frame; your edits remain in your browser page and are not uploaded.

JavaScript · Beginner

Live Clock

Display the current time and update it once per second.

<p>Current time: <time id="clock">--:--:--</time></p>
<script>
  const clock = document.querySelector('#clock');
  function updateClock() {
    clock.textContent = new Date().toLocaleTimeString();
  }
  updateClock();
  setInterval(updateClock, 1000);
</script>
How it works

How it works

Display the current time and update it once per second. Start by changing the sample content to fit your project, then test the result at a narrow screen width and with keyboard navigation. Keep the markup, styling, and behavior easy to identify, and remove any sample values you do not need.

Related styling example
time{font:700 1.5rem ui-monospace,monospace;color:#1d4ed8}
JavaScript · Beginner

Character Counter

Count the characters typed into a textarea and announce the count.

<label for="bio">Short bio</label>
<textarea id="bio" maxlength="160"></textarea>
<p><span id="count" aria-live="polite">0</span>/160 characters</p>
<script>
  const bio = document.querySelector('#bio');
  const count = document.querySelector('#count');
  bio.addEventListener('input', () => {
    count.textContent = bio.value.length;
  });
</script>
How it works

How it works

Count the characters typed into a textarea and announce the count. Start by changing the sample content to fit your project, then test the result at a narrow screen width and with keyboard navigation. Keep the markup, styling, and behavior easy to identify, and remove any sample values you do not need.

Related styling example
textarea{display:block;width:100%;max-width:420px;min-height:100px;padding:.75rem;border:1px solid #cbd5e1;border-radius:8px}
JavaScript · Beginner

Dark Mode Toggle

Toggle a theme class and update the button label accessibly.

<button id="theme-toggle" type="button" aria-pressed="false">Enable dark mode</button>
<script>
  const toggle = document.querySelector('#theme-toggle');
  toggle.addEventListener('click', () => {
    const enabled = document.body.classList.toggle('dark-mode');
    toggle.setAttribute('aria-pressed', String(enabled));
    toggle.textContent = enabled ? 'Disable dark mode' : 'Enable dark mode';
  });
</script>
How it works

How it works

Toggle a theme class and update the button label accessibly. Start by changing the sample content to fit your project, then test the result at a narrow screen width and with keyboard navigation. Keep the markup, styling, and behavior easy to identify, and remove any sample values you do not need.

Related styling example
body{font-family:system-ui,sans-serif;background:white;color:#172033;padding:1rem}body.dark-mode{background:#111827;color:#f9fafb}button{padding:.7rem 1rem;border-radius:8px;cursor:pointer}
JavaScript · Beginner

Form Validation

Check a form field and show a helpful message before continuing.

<form id="signup">
  <label for="username">Username</label>
  <input id="username" required minlength="3">
  <button>Continue</button>
  <p id="feedback" aria-live="polite"></p>
</form>
<script>
  const form = document.querySelector('#signup');
  const feedback = document.querySelector('#feedback');
  form.addEventListener('submit', event => {
    if (!form.checkValidity()) {
      event.preventDefault();
      feedback.textContent = 'Please enter at least 3 characters.';
    }
  });
</script>
How it works

How it works

Check a form field and show a helpful message before continuing. Start by changing the sample content to fit your project, then test the result at a narrow screen width and with keyboard navigation. Keep the markup, styling, and behavior easy to identify, and remove any sample values you do not need.

Related styling example
form{display:grid;gap:.6rem;max-width:340px}input,button{padding:.7rem;font:inherit}#feedback{color:#b91c1c}
JavaScript · Beginner

Random Quote Generator

Choose a random item from an array when a button is clicked.

<blockquote id="quote">Small steps create progress.</blockquote>
<button id="new-quote" type="button">New quote</button>
<script>
  const quotes = ['Keep learning.', 'Build, test, improve.', 'Small steps create progress.'];
  document.querySelector('#new-quote').addEventListener('click', () => {
    document.querySelector('#quote').textContent = quotes[Math.floor(Math.random() * quotes.length)];
  });
</script>
How it works

How it works

Choose a random item from an array when a button is clicked. Start by changing the sample content to fit your project, then test the result at a narrow screen width and with keyboard navigation. Keep the markup, styling, and behavior easy to identify, and remove any sample values you do not need.

Related styling example
blockquote{font-size:1.25rem;line-height:1.6;padding:1rem;border-left:4px solid #2563eb;background:#eff6ff}
JavaScript · Beginner

Text Case Converter

Convert entered text to uppercase or lowercase with built-in string methods.

<label for="source-text">Enter text</label>
<input id="source-text" value="Hello web developer">
<button id="upper" type="button">Uppercase</button>
<button id="lower" type="button">Lowercase</button>
<script>
  const source = document.querySelector('#source-text');
  document.querySelector('#upper').addEventListener('click', () => source.value = source.value.toUpperCase());
  document.querySelector('#lower').addEventListener('click', () => source.value = source.value.toLowerCase());
</script>
How it works

How it works

Convert entered text to uppercase or lowercase with built-in string methods. Start by changing the sample content to fit your project, then test the result at a narrow screen width and with keyboard navigation. Keep the markup, styling, and behavior easy to identify, and remove any sample values you do not need.

Related styling example
input{display:block;width:min(100%,420px);padding:.7rem;margin:.5rem 0}button{padding:.65rem .9rem;margin-right:.4rem}
JavaScript · Beginner

Simple Countdown

Count down to zero and stop the timer when it finishes.

<p id="countdown" aria-live="polite">5</p>
<script>
  let remaining = 5;
  const output = document.querySelector('#countdown');
  const timer = setInterval(() => {
    remaining -= 1;
    output.textContent = remaining;
    if (remaining <= 0) {
      clearInterval(timer);
      output.textContent = 'Done!';
    }
  }, 1000);
</script>
How it works

How it works

Count down to zero and stop the timer when it finishes. Start by changing the sample content to fit your project, then test the result at a narrow screen width and with keyboard navigation. Keep the markup, styling, and behavior easy to identify, and remove any sample values you do not need.

Related styling example
#countdown{font-size:2rem;font-weight:800;color:#2563eb}
JavaScript · Beginner

Copy Text to Clipboard

Copy a short value using the Clipboard API with a fallback message.

<input id="copy-value" value="Hello from HTMLToddler">
<button id="copy-button" type="button">Copy text</button>
<p id="copy-status" aria-live="polite"></p>
<script>
  document.querySelector('#copy-button').addEventListener('click', async () => {
    const value = document.querySelector('#copy-value').value;
    try {
      await navigator.clipboard.writeText(value);
      document.querySelector('#copy-status').textContent = 'Copied!';
    } catch {
      document.querySelector('#copy-status').textContent = 'Select and copy the text manually.';
    }
  });
</script>
How it works

How it works

Copy a short value using the Clipboard API with a fallback message. Start by changing the sample content to fit your project, then test the result at a narrow screen width and with keyboard navigation. Keep the markup, styling, and behavior easy to identify, and remove any sample values you do not need.

Related styling example
input{padding:.7rem;border:1px solid #cbd5e1;border-radius:8px}button{padding:.7rem 1rem;background:#2563eb;color:white;border:0;border-radius:8px}
JavaScript · Beginner

Simple Tabs

Switch visible panels and keep selected state reflected in the interface.

<button data-tab="one" aria-selected="true">First</button>
<button data-tab="two" aria-selected="false">Second</button>
<section id="one">Content for the first tab.</section>
<section id="two" hidden>Content for the second tab.</section>
<script>
  document.querySelectorAll('[data-tab]').forEach(button => {
    button.addEventListener('click', () => {
      document.querySelectorAll('[data-tab]').forEach(item => item.setAttribute('aria-selected', String(item === button)));
      document.querySelectorAll('section#one, section#two').forEach(panel => panel.hidden = panel.id !== button.dataset.tab);
    });
  });
</script>
How it works

How it works

Switch visible panels and keep selected state reflected in the interface. Start by changing the sample content to fit your project, then test the result at a narrow screen width and with keyboard navigation. Keep the markup, styling, and behavior easy to identify, and remove any sample values you do not need.

Related styling example
[data-tab]{padding:.7rem 1rem;border:1px solid #cbd5e1;background:white;cursor:pointer}[aria-selected="true"]{background:#dbeafe;border-color:#2563eb}section{padding:1rem;margin-top:.75rem;border:1px solid #e2e8f0}
JavaScript · Beginner

Tiny To-Do List

Add tasks to a list using DOM methods and textContent.

<form id="task-form"><label for="task">New task</label><input id="task" required><button>Add</button></form>
<ul id="tasks"></ul>
<script>
  document.querySelector('#task-form').addEventListener('submit', event => {
    event.preventDefault();
    const input = document.querySelector('#task');
    const item = document.createElement('li');
    item.textContent = input.value.trim();
    if (item.textContent) document.querySelector('#tasks').append(item);
    input.value = '';
  });
</script>
How it works

How it works

Add tasks to a list using DOM methods and textContent. Start by changing the sample content to fit your project, then test the result at a narrow screen width and with keyboard navigation. Keep the markup, styling, and behavior easy to identify, and remove any sample values you do not need.

Related styling example
form{display:flex;gap:.5rem;flex-wrap:wrap}input{padding:.6rem;border:1px solid #cbd5e1;border-radius:7px}li{margin:.5rem 0}
JavaScript · Beginner

Fetch JSON Data

Request JSON from an API and handle loading and error states.

<button id="load" type="button">Load example data</button>
<p id="result" aria-live="polite"></p>
<script>
  document.querySelector('#load').addEventListener('click', async () => {
    const result = document.querySelector('#result');
    result.textContent = 'Loading…';
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
      if (!response.ok) throw new Error('Request failed');
      const data = await response.json();
      result.textContent = data.title;
    } catch {
      result.textContent = 'Could not load data. Check your connection and try again.';
    }
  });
</script>
How it works

How it works

Request JSON from an API and handle loading and error states. Start by changing the sample content to fit your project, then test the result at a narrow screen width and with keyboard navigation. Keep the markup, styling, and behavior easy to identify, and remove any sample values you do not need.

Related styling example
#result{padding:1rem;background:#f1f5f9;border-radius:8px;line-height:1.6}
JavaScript · Beginner

Save a Note Locally

Store a small note in the browser and restore it on the next visit.

<label for="note">Your note</label>
<textarea id="note"></textarea>
<button id="save-note" type="button">Save note</button>
<p id="save-status" aria-live="polite"></p>
<script>
  const note = document.querySelector('#note');
  note.value = localStorage.getItem('beginner-note') || '';
  document.querySelector('#save-note').addEventListener('click', () => {
    localStorage.setItem('beginner-note', note.value);
    document.querySelector('#save-status').textContent = 'Saved in this browser.';
  });
</script>
How it works

How it works

Store a small note in the browser and restore it on the next visit. Start by changing the sample content to fit your project, then test the result at a narrow screen width and with keyboard navigation. Keep the markup, styling, and behavior easy to identify, and remove any sample values you do not need.

Related styling example
textarea{display:block;width:min(100%,480px);min-height:120px;padding:.8rem;border:1px solid #cbd5e1;border-radius:8px}button{margin-top:.7rem;padding:.7rem 1rem}

Practice note: examples are educational starting points. Check the code, replace placeholder data, and test accessibility, responsive behavior, and any required security controls before using it in a live project.

Frequently Asked Questions

What can JavaScript do on a website?

It can respond to events, update page content, validate input, store simple preferences, and request data from APIs.

Do I need to learn HTML and CSS first?

Basic HTML and CSS make JavaScript easier to understand, but you can learn all three together through small projects.

Why is my JavaScript not running?

Check the script path, browser console, selector names, syntax, and whether the script runs after the relevant elements exist.

Is localStorage secure for passwords?

No. Do not store passwords, private tokens, or other secrets in localStorage.

Does client-side validation secure a form?

No. Client-side checks improve usability, but a server must validate and authorize submitted data independently.