agyanadda@gmail.com

JavaScript Examples

39 examples 38 you can try online 38 topics

Learn by doing. Every example below can be opened in our online editor — change the code, press Run and see the result instantly.

Open the Try it Now editor »

JS Introduction

JavaScript Basics · 1 example
Example — Change text with a click HTML
<h2 id="msg">Hello!</h2>
<button onclick="document.getElementById('msg').textContent = 'You clicked the button!'">Click me</button>

JavaScript finds the heading by its id and changes its text.

JS Where To

JavaScript Basics · 1 example
Example — Script at the end of body HTML
<!DOCTYPE html>
<html>
<body>
  <h2>My Page</h2>
  <p id="demo"></p>

  <script>
    document.getElementById('demo').textContent = 'This text was added by JavaScript.';
  </script>
</body>
</html>

JS Output

JavaScript Basics · 1 example
Example — Different output methods HTML
<p id="a"></p>
<p id="b"></p>

<script>
  document.getElementById('a').textContent = '<b>textContent</b> shows tags as text';
  document.getElementById('b').innerHTML = '<b>innerHTML</b> renders the tags';
  console.log('Open the console (F12) to see this message');
</script>

JS Syntax and Comments

JavaScript Basics · 1 example
Example — Statements and comments HTML
<p id="out"></p>

<script>
  // Price of one item
  let price = 250;
  let qty = 4; // number of items

  /*
    Calculate the total
    and show it on the page
  */
  let total = price * qty;
  document.getElementById('out').textContent = 'Total: ₹' + total;
</script>

JS Variables

JavaScript Basics · 1 example
Example — let and const HTML
<p id="out"></p>

<script>
  const city = 'Gaya';
  let score = 10;
  score = score + 5;

  document.getElementById('out').textContent = city + ' – score: ' + score;
  // city = 'Patna'; // Error: const cannot be reassigned
</script>

JS Data Types

JavaScript Basics · 1 example
Example — Checking types with typeof HTML
<pre id="out"></pre>

<script>
  const values = ['Hello', 42, true, undefined, null, [1, 2], { a: 1 }];
  let text = '';
  for (const v of values) {
    text += JSON.stringify(v) + ' → ' + typeof v + '\n';
  }
  document.getElementById('out').textContent = text;
</script>

Note: typeof null is "object" — a famous old JavaScript quirk.

JS Operators

JavaScript Basics · 1 example
Example — Operators in action HTML
<pre id="out"></pre>

<script>
  const a = 10, b = 3;
  const lines = [
    'a + b = ' + (a + b),
    'a % b = ' + (a % b),
    'a ** 2 = ' + (a ** 2),
    '5 == "5" → ' + (5 == '5'),
    '5 === "5" → ' + (5 === '5'),
    'a > 5 && b > 5 → ' + (a > 5 && b > 5),
    'Result: ' + (a >= 10 ? 'Pass' : 'Fail')
  ];
  document.getElementById('out').textContent = lines.join('\n');
</script>

JS Strings

Strings and Numbers · 1 example
Example — String basics HTML
<pre id="out"></pre>

<script>
  const name = 'AgyanAdda';
  const msg = 'It\'s easy to learn';
  const out = [
    'Length: ' + name.length,
    'First letter: ' + name[0],
    'Last letter: ' + name[name.length - 1],
    msg,
    'Joined: ' + name + ' ' + 'Tutorials'
  ];
  document.getElementById('out').textContent = out.join('\n');
</script>

JS String Methods

Strings and Numbers · 1 example
Example — Cleaning user input HTML
<pre id="out"></pre>

<script>
  const input = '   Asha Kumari   ';
  const clean = input.trim();
  const out = [
    'Trimmed: "' + clean + '"',
    'Upper: ' + clean.toUpperCase(),
    'Has "Kumari": ' + clean.includes('Kumari'),
    'First name: ' + clean.split(' ')[0],
    'Username: ' + clean.toLowerCase().replaceAll(' ', '_'),
    'Roll no: ' + '7'.padStart(4, '0')
  ];
  document.getElementById('out').textContent = out.join('\n');
</script>

JS Template Literals

Strings and Numbers · 1 example
Example — Building HTML with template literals HTML
<div id="list"></div>

<script>
  const courses = [
    { name: 'HTML', topics: 33 },
    { name: 'CSS', topics: 39 },
    { name: 'JavaScript', topics: 40 }
  ];
  let html = '';
  for (const c of courses) {
    html += `<p><strong>${c.name}</strong> – ${c.topics} topics</p>`;
  }
  document.getElementById('list').innerHTML = html;
</script>

JS Numbers and Math

Strings and Numbers · 1 example
Example — Dice roller HTML
<button onclick="roll()">Roll the dice</button>
<h2 id="dice">?</h2>
<p id="info"></p>

<script>
  function roll() {
    const n = Math.floor(Math.random() * 6) + 1;
    document.getElementById('dice').textContent = n;
  }
  document.getElementById('info').textContent =
    'Price with GST: ₹' + (499 * 1.18).toFixed(2);
</script>

JS Type Conversion

Strings and Numbers · 1 example
Example — Adding two inputs correctly HTML
<input id="x" value="10" size="4"> +
<input id="y" value="5" size="4">
<button onclick="add()">Add</button>
<pre id="out"></pre>

<script>
  function add() {
    const x = document.getElementById('x').value;
    const y = document.getElementById('y').value;
    document.getElementById('out').textContent =
      'Without converting: ' + (x + y) + '\n' +
      'With Number(): ' + (Number(x) + Number(y));
  }
</script>

JS If Else

Conditions and Loops · 1 example
Example — Grade calculator HTML
<input id="marks" type="number" value="72"> 
<button onclick="check()">Get grade</button>
<p id="out"></p>

<script>
  function check() {
    const marks = Number(document.getElementById('marks').value);
    let grade;
    if (marks >= 90) {
      grade = 'A+';
    } else if (marks >= 75) {
      grade = 'A';
    } else if (marks >= 60) {
      grade = 'B';
    } else if (marks >= 33) {
      grade = 'C';
    } else {
      grade = 'Fail';
    }
    document.getElementById('out').textContent = 'Grade: ' + grade;
  }
</script>

JS Switch

Conditions and Loops · 1 example
Example — Day name from a number HTML
<p id="out"></p>

<script>
  const dayNum = new Date().getDay();
  let dayName;
  switch (dayNum) {
    case 0: dayName = 'Sunday'; break;
    case 1: dayName = 'Monday'; break;
    case 2: dayName = 'Tuesday'; break;
    case 3: dayName = 'Wednesday'; break;
    case 4: dayName = 'Thursday'; break;
    case 5: dayName = 'Friday'; break;
    case 6: dayName = 'Saturday'; break;
    default: dayName = 'Unknown';
  }
  document.getElementById('out').textContent = 'Today is ' + dayName;
</script>

JS For Loop

Conditions and Loops · 2 examples
Example — Multiplication table HTML
<input id="n" type="number" value="7" style="width:60px">
<button onclick="table()">Show table</button>
<pre id="out"></pre>

<script>
  function table() {
    const n = Number(document.getElementById('n').value);
    let text = '';
    for (let i = 1; i <= 10; i++) {
      text += `${n} x ${i} = ${n * i}\n`;
    }
    document.getElementById('out').textContent = text;
  }
  table();
</script>
Example — for...of with continue HTML
<pre id="out"></pre>

<script>
  const marks = [45, 82, 30, 91, 67];
  let text = 'Passed marks:\n';
  for (const m of marks) {
    if (m < 33) continue; // skip failed marks
    text += m + '\n';
  }
  document.getElementById('out').textContent = text;
</script>

JS While Loop

Conditions and Loops · 1 example
Example — Doubling until 1000 HTML
<pre id="out"></pre>

<script>
  let amount = 1;
  let days = 0;
  let text = '';
  while (amount < 1000) {
    amount *= 2;
    days++;
    text += `Day ${days}: ₹${amount}\n`;
  }
  text += `\nIt took ${days} days to cross ₹1000.`;
  document.getElementById('out').textContent = text;
</script>

JS Functions

Functions · 1 example
Example — Function with parameters and return HTML
<pre id="out"></pre>

<script>
  function calcTotal(price, qty = 1, gst = 18) {
    const subtotal = price * qty;
    return subtotal + subtotal * gst / 100;
  }

  document.getElementById('out').textContent =
    'Pen x 1: ₹' + calcTotal(10) + '\n' +
    'Book x 3: ₹' + calcTotal(200, 3) + '\n' +
    'Bag x 2 (12% GST): ₹' + calcTotal(500, 2, 12);
</script>

JS Arrow Functions

Functions · 1 example
Example — Arrow functions in practice HTML
<pre id="out"></pre>

<script>
  const square = n => n * n;
  const greet = (name = 'Guest') => `Welcome, ${name}!`;
  const toPrice = amount => {
    const withTax = amount * 1.18;
    return '₹' + withTax.toFixed(2);
  };

  const prices = [100, 250, 999].map(p => toPrice(p));

  document.getElementById('out').textContent =
    square(9) + '\n' + greet('Ravi') + '\n' + prices.join(', ');
</script>

JS Scope

Functions · 1 example
Example — Block scope and a closure HTML
<button id="btn">Clicked 0 times</button>
<pre id="out"></pre>

<script>
  const site = 'AgyanAdda'; // global

  if (true) {
    let inside = 'only in this block';
  }
  document.getElementById('out').textContent =
    'site: ' + site + '\ninside: ' + (typeof inside);

  function makeCounter() {
    let count = 0; // private to the closure
    return () => ++count;
  }
  const next = makeCounter();
  document.getElementById('btn').onclick = function () {
    this.textContent = 'Clicked ' + next() + ' times';
  };
</script>

JS Arrays

Arrays and Objects · 1 example
Example — Shopping list HTML
<input id="item" placeholder="Add item">
<button onclick="addItem()">Add</button>
<button onclick="removeLast()">Remove last</button>
<ol id="list"></ol>

<script>
  const items = ['Milk', 'Bread'];

  function render() {
    document.getElementById('list').innerHTML =
      items.map(i => `<li>${i}</li>`).join('');
  }
  function addItem() {
    const input = document.getElementById('item');
    if (input.value.trim()) items.push(input.value.trim());
    input.value = '';
    render();
  }
  function removeLast() {
    items.pop();
    render();
  }
  render();
</script>

JS Array Methods

Arrays and Objects · 1 example
Example — map, filter and reduce HTML
<pre id="out"></pre>

<script>
  const students = [
    { name: 'Asha', marks: 82 },
    { name: 'Ravi', marks: 45 },
    { name: 'Neha', marks: 91 },
    { name: 'Aman', marks: 28 }
  ];

  const names = students.map(s => s.name);
  const passed = students.filter(s => s.marks >= 33);
  const topper = students.find(s => s.marks > 90);
  const total = students.reduce((sum, s) => sum + s.marks, 0);
  const sorted = [...students].sort((a, b) => b.marks - a.marks);

  document.getElementById('out').textContent = [
    'Names: ' + names.join(', '),
    'Passed: ' + passed.map(s => s.name).join(', '),
    'Topper: ' + topper.name,
    'Average: ' + (total / students.length).toFixed(1),
    'Rank list: ' + sorted.map(s => s.name).join(' > ')
  ].join('\n');
</script>

JS Objects

Arrays and Objects · 1 example
Example — Student object HTML
<pre id="out"></pre>

<script>
  const student = {
    name: 'Asha',
    marks: { html: 88, css: 92, js: 79 },
    average() {
      const list = Object.values(this.marks);
      return list.reduce((a, b) => a + b, 0) / list.length;
    }
  };

  student.city = 'Gaya';
  let text = `${student.name} from ${student.city}\n`;
  for (const [subject, mark] of Object.entries(student.marks)) {
    text += `${subject.toUpperCase()}: ${mark}\n`;
  }
  text += 'Average: ' + student.average().toFixed(1);
  document.getElementById('out').textContent = text;
</script>

JS Destructuring and Spread

Arrays and Objects · 1 example
Example — Destructuring and spread HTML
<pre id="out"></pre>

<script>
  const user = { name: 'Ravi', role: 'Student', city: 'Patna' };
  const { name, role, country = 'India' } = user;

  const [gold, silver, ...others] = ['Neha', 'Asha', 'Aman', 'Ravi'];

  const updated = { ...user, role: 'Mentor' };
  const sum = (...n) => n.reduce((a, b) => a + b, 0);

  document.getElementById('out').textContent = [
    `${name} – ${role} – ${country}`,
    `Gold: ${gold}, Silver: ${silver}, Others: ${others.join(', ')}`,
    'Updated role: ' + updated.role + ' (original: ' + user.role + ')',
    'Sum: ' + sum(5, 10, 15),
    'Max: ' + Math.max(...[4, 19, 7])
  ].join('\n');
</script>

JS JSON

Arrays and Objects · 1 example
Example — stringify and parse HTML
<pre id="out"></pre>

<script>
  const course = { title: 'JavaScript', topics: 40, free: true, tags: ['web', 'frontend'] };

  const text = JSON.stringify(course, null, 2);
  const back = JSON.parse(text);

  document.getElementById('out').textContent =
    'As JSON text:\n' + text + '\n\nParsed back – title: ' + back.title + ', type: ' + typeof back;
</script>

JS DOM

Working with the Page · 1 example
Example — Select and change elements HTML
<style>
  .highlight { background: #fff3cd; font-weight: bold; }
</style>

<h2 id="title">DOM Demo</h2>
<ul>
  <li>HTML</li>
  <li>CSS</li>
  <li>JavaScript</li>
</ul>
<button onclick="change()">Change page</button>

<script>
  function change() {
    document.getElementById('title').textContent = 'Changed with the DOM!';
    document.querySelector('h2').style.color = '#1f386b';
    document.querySelectorAll('li').forEach(li => li.classList.toggle('highlight'));
  }
</script>

JS Create and Remove Elements

Working with the Page · 1 example
Example — To-do list HTML
<style>
  li { margin: 4px 0; }
  li button { margin-left: 8px; color: crimson; border: none; background: none; cursor: pointer; }
</style>

<input id="task" placeholder="New task">
<button id="add">Add</button>
<ul id="todos"></ul>

<script>
  const list = document.getElementById('todos');
  const input = document.getElementById('task');

  document.getElementById('add').addEventListener('click', () => {
    const text = input.value.trim();
    if (!text) return;

    const li = document.createElement('li');
    li.textContent = text;

    const del = document.createElement('button');
    del.textContent = '✕';
    del.addEventListener('click', () => li.remove());

    li.append(del);
    list.append(li);
    input.value = '';
  });
</script>

JS Events

Working with the Page · 1 example
Example — Live character counter HTML
<textarea id="msg" rows="3" cols="40" maxlength="100" placeholder="Type here..."></textarea>
<p id="count">0 / 100</p>
<p id="key"></p>

<script>
  const msg = document.getElementById('msg');

  msg.addEventListener('input', e => {
    document.getElementById('count').textContent = e.target.value.length + ' / 100';
  });

  msg.addEventListener('keydown', e => {
    document.getElementById('key').textContent = 'Last key: ' + e.key;
  });
</script>

JS Form Validation

Working with the Page · 1 example
Example — Validate a sign-up form HTML
<style>
  .err { color: crimson; font-size: 13px; display: block; }
  input { display: block; margin-top: 8px; padding: 6px; }
</style>

<form id="signup" novalidate>
  <input id="name" placeholder="Name"><span class="err" id="nameErr"></span>
  <input id="email" placeholder="Email"><span class="err" id="emailErr"></span>
  <input id="mobile" placeholder="Mobile"><span class="err" id="mobileErr"></span>
  <button>Sign up</button>
</form>
<p id="ok" style="color:green"></p>

<script>
  document.getElementById('signup').addEventListener('submit', e => {
    e.preventDefault();
    const val = id => document.getElementById(id).value.trim();
    const show = (id, msg) => document.getElementById(id).textContent = msg;
    let valid = true;

    if (val('name').length < 3) { show('nameErr', 'Name must be at least 3 letters'); valid = false; } else show('nameErr', '');
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val('email'))) { show('emailErr', 'Enter a valid email'); valid = false; } else show('emailErr', '');
    if (!/^[6-9]\d{9}$/.test(val('mobile'))) { show('mobileErr', 'Enter a 10-digit mobile number'); valid = false; } else show('mobileErr', '');

    document.getElementById('ok').textContent = valid ? 'All good! Form can be sent.' : '';
  });
</script>

JS Timers

Working with the Page · 1 example
Example — Countdown timer HTML
<h1 id="time">10</h1>
<button id="start">Start</button>
<button id="stop">Stop</button>

<script>
  let seconds = 10;
  let timer = null;
  const show = () => document.getElementById('time').textContent = seconds;

  document.getElementById('start').onclick = () => {
    if (timer) return;
    timer = setInterval(() => {
      seconds--;
      show();
      if (seconds === 0) {
        clearInterval(timer);
        timer = null;
        document.getElementById('time').textContent = 'Time up!';
      }
    }, 1000);
  };

  document.getElementById('stop').onclick = () => {
    clearInterval(timer);
    timer = null;
  };
</script>

JS Local Storage

Working with the Page · 1 example
Example — Remember a name HTML
<input id="name" placeholder="Your name">
<button id="save">Save</button>
<button id="forget">Forget</button>
<h3 id="hello"></h3>

<script>
  const hello = document.getElementById('hello');
  const show = () => {
    let name = null;
    try { name = localStorage.getItem('name'); } catch (e) {}
    hello.textContent = name ? `Welcome back, ${name}!` : 'Hello, guest!';
  };

  document.getElementById('save').onclick = () => {
    try { localStorage.setItem('name', document.getElementById('name').value); } catch (e) {}
    show();
  };
  document.getElementById('forget').onclick = () => {
    try { localStorage.removeItem('name'); } catch (e) {}
    show();
  };
  show();
</script>

Save a name, then reload the page — it is still remembered.

JS Callbacks and Promises

Asynchronous JavaScript · 1 example
Example — Creating and using a Promise HTML
<button id="go">Check result</button>
<p id="out"></p>

<script>
  function getResult(roll) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (roll > 0) resolve({ roll, marks: Math.floor(Math.random() * 100) });
        else reject('Invalid roll number');
      }, 1000);
    });
  }

  document.getElementById('go').onclick = () => {
    const out = document.getElementById('out');
    out.textContent = 'Loading...';
    getResult(101)
      .then(r => out.textContent = `Roll ${r.roll}: ${r.marks} marks`)
      .catch(err => out.textContent = 'Error: ' + err)
      .finally(() => console.log('Request finished'));
  };
</script>

JS Async Await

Asynchronous JavaScript · 1 example
Example — Step by step with await HTML
<button id="go">Place order</button>
<pre id="out"></pre>

<script>
  const wait = (ms, msg) => new Promise(r => setTimeout(() => r(msg), ms));
  const out = document.getElementById('out');

  async function placeOrder() {
    out.textContent = '';
    try {
      out.textContent += await wait(700, '1. Order received') + '\n';
      out.textContent += await wait(700, '2. Payment confirmed') + '\n';
      out.textContent += await wait(700, '3. Packed and shipped') + '\n';
      out.textContent += 'Done!';
    } catch (err) {
      out.textContent += 'Something went wrong: ' + err;
    }
  }

  document.getElementById('go').onclick = placeOrder;
</script>

JS Fetch API

Asynchronous JavaScript · 1 example
Example — Load users from an API HTML
<button id="load">Load users</button>
<ul id="users"></ul>
<p id="msg"></p>

<script>
  document.getElementById('load').onclick = async () => {
    const msg = document.getElementById('msg');
    const list = document.getElementById('users');
    msg.textContent = 'Loading...';
    list.innerHTML = '';
    try {
      const res = await fetch('https://jsonplaceholder.typicode.com/users');
      if (!res.ok) throw new Error('HTTP ' + res.status);
      const users = await res.json();
      for (const u of users) {
        const li = document.createElement('li');
        li.textContent = `${u.name} – ${u.address.city}`;
        list.append(li);
      }
      msg.textContent = users.length + ' users loaded.';
    } catch (err) {
      msg.textContent = 'Could not load data: ' + err.message;
    }
  };
</script>

Uses the free JSONPlaceholder test API.

JS Dates

Modern JS and Best Practices · 1 example
Example — Live clock and days left HTML
<h2 id="clock"></h2>
<p id="today"></p>
<p id="left"></p>

<script>
  function tick() {
    const now = new Date();
    document.getElementById('clock').textContent = now.toLocaleTimeString('en-IN');
    document.getElementById('today').textContent =
      now.toLocaleDateString('en-IN', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });

    const newYear = new Date(now.getFullYear() + 1, 0, 1);
    const days = Math.ceil((newYear - now) / (1000 * 60 * 60 * 24));
    document.getElementById('left').textContent = days + ' days to New Year';
  }
  tick();
  setInterval(tick, 1000);
</script>

JS Error Handling

Modern JS and Best Practices · 1 example
Example — Safe JSON parsing HTML
<textarea id="json" rows="3" cols="40">{"name": "Asha", "age": 20}</textarea><br>
<button id="parse">Parse</button>
<pre id="out"></pre>

<script>
  document.getElementById('parse').onclick = () => {
    const out = document.getElementById('out');
    try {
      const obj = JSON.parse(document.getElementById('json').value);
      if (obj.age < 0) throw new Error('Age cannot be negative');
      out.textContent = 'OK: ' + obj.name + ', ' + obj.age;
      out.style.color = 'green';
    } catch (err) {
      out.textContent = err.name + ': ' + err.message;
      out.style.color = 'crimson';
    }
  };
</script>

Try removing a quote or setting age to -5, then press Parse.

JS Classes

Modern JS and Best Practices · 1 example
Example — Bank account class HTML
<pre id="out"></pre>

<script>
  class Account {
    constructor(owner, balance = 0) {
      this.owner = owner;
      this.balance = balance;
    }
    deposit(amount) { this.balance += amount; return this; }
    withdraw(amount) {
      if (amount > this.balance) throw new Error('Insufficient balance');
      this.balance -= amount;
      return this;
    }
    toString() { return `${this.owner}: ₹${this.balance}`; }
  }

  class Savings extends Account {
    constructor(owner, balance, rate) {
      super(owner, balance);
      this.rate = rate;
    }
    addInterest() { return this.deposit(this.balance * this.rate / 100); }
  }

  const acc = new Savings('Ravi', 1000, 5);
  acc.deposit(500).addInterest();
  let text = acc.toString();
  try { acc.withdraw(99999); } catch (e) { text += '\n' + e.message; }
  document.getElementById('out').textContent = text;
</script>

JS Modules

Modern JS and Best Practices · 1 example
Example — Export and import (two files) JavaScript
// ---- file: utils.js ----
export const GST = 18;
export function withGst(price) {
  return price + price * GST / 100;
}
export default function formatINR(n) {
  return '₹' + n.toLocaleString('en-IN');
}

// ---- file: app.js ----
import formatINR, { withGst, GST } from './utils.js';

console.log(`Price with ${GST}% GST:`, formatINR(withGst(1000)));

// ---- index.html ----
// <script type="module" src="app.js"></script>

Modules need separate files and a web server, so this example is for reading, not for the Try it editor.

JS Best Practices

Modern JS and Best Practices · 1 example
Example — Clean code: before and after HTML
<pre id="out"></pre>

<script>
  // Before: unclear names, ==, nested ifs
  // function c(a) { if (a) { if (a.m == '33') { return 'p'; } } }

  // After: clear names, early return, strict equality
  const PASS_MARK = 33;

  function getResult(student) {
    if (!student) return 'No data';
    return student.marks >= PASS_MARK ? 'Pass' : 'Fail';
  }

  const students = [
    { name: 'Asha', marks: 82 },
    { name: 'Aman', marks: 21 }
  ];

  document.getElementById('out').textContent = students
    .map(s => `${s.name}: ${getResult(s)}`)
    .join('\n');
</script>