Practical JavaScript Examples with Source Code

⚡ Smart Summary

Practical Code Examples using JavaScript demonstrate how loops, form validation, and events solve everyday browser tasks. This article presents a multiplication table generator, a complete registration form validator, a hover triggered popup, a live digital clock, and the practices that keep such scripts reliable.

  • ✖️ Nested Loops: The multiplication table builds an HTML string with an outer row loop and an inner column loop.
  • 📝 Form Validation: Parallel arrays link each input to its own error container, so messages appear beside the field that failed.
  • 📧 Email Rule: Position checks on the at sign and the final dot reject malformed addresses before submission.
  • 🖱️ Event Handling: addEventListener attaches behaviour to an element without placing script inside the markup.
  • Timed Updates: setInterval repeats a function on a fixed schedule, which drives the live clock example.
  • 🔐 Server Rule: Client-side checks improve the experience only, and every value must be validated again on the server.
  • 🧹 Modern Practice: Replace document.write and implicit globals with textContent, let, and const in new code.

JavaScript Examples with Source Code

What You Will Build in These JavaScript Examples

Each example below is a complete HTML page that runs in any browser without a build step or external library. Together they cover the three skills that appear in almost every browser script: generating markup from data, validating user input, and reacting to events.

Example Concept Practised Key Methods Used
Multiplication table Nested loops and string building prompt, for, while, document.write
Form validation Arrays, conditions, and DOM updates getElementById, indexOf, lastIndexOf, innerHTML
Popup message Event handling addEventListener, alert
Digital clock Timers and date formatting setInterval, Date, padStart, textContent

Basic familiarity with JavaScript syntax is assumed. If loops are still unfamiliar, read how to use loops in JavaScript before starting.

Example#1: JavaScript Multiplication Table

Create a simple multiplication table asking the user for the number of rows and columns.

Solution:

<html>
<head>
  <title>Multiplication Table</title>
  <script type="text/javascript">
    var rows = prompt("How many rows for your multiplication table?");
    var cols = prompt("How many columns for your multiplication table?");
    if(rows == "" || rows == null)
   		 rows = 10;
    if(cols== "" || cols== null)
   		 cols = 10;
    createTable(rows, cols);
    function createTable(rows, cols)
    {
      var j=1;
      var output = "<table border='1' width='500' cellspacing='0' cellpadding='5'>";
      for(i=1;i<=rows;i++)
      {
    	output = output + "<tr>";
        while(j<=cols)
        {
  		  output = output + "<td>" + i*j + "</td>";
   		  j = j+1;
   		}
   		 output = output + "</tr>";
   		 j = 1;
    }
    output = output + "</table>";
    document.write(output);
    }
  </script>
</head>
<body>
</body>
</html>

Output (3 rows and 4 columns):

1   2   3   4
2   4   6   8
3   6   9  12

Code explanation: The outer for loop creates one table row per iteration, while the inner while loop fills that row with one cell per column. The counter j is reset to 1 after each row, which is the step most beginners forget. Without that reset, only the first row would contain any cells.

💡 Tip: The prompt function always returns a string. The expression i*j works because JavaScript converts both operands to numbers for multiplication, but a comparison such as rows > 5 would compare text. Wrap the input in Number() when the value is used for arithmetic and comparison alike.

Example#2: JS Forms Example

Create a sample form program that collects the first name, last name, email, user id, password, and confirm password from the user. All the inputs are mandatory and the email address entered should be in the correct format. Also, the values entered in the password and confirm password textboxes should be the same. After validating using JavaScript, display proper error messages in red just next to the textbox where there is an error.

Solution with Source Code:

<html>
<head>
  <title>Form Validation</title>
  <script type="text/javascript">
    var divs = new Array();
    divs[0] = "errFirst";
    divs[1] = "errLast";
    divs[2] = "errEmail";
    divs[3] = "errUid";
    divs[4] = "errPassword";
    divs[5] = "errConfirm";
    function validate()
	{
      var inputs = new Array();
      inputs[0] = document.getElementById('first').value;
      inputs[1] = document.getElementById('last').value;
      inputs[2] = document.getElementById('email').value;
      inputs[3] = document.getElementById('uid').value;
      inputs[4] = document.getElementById('password').value;
      inputs[5] = document.getElementById('confirm').value;
      var errors = new Array();
      errors[0] = "<span style='color:red'>Please enter your first name!</span>";
      errors[1] = "<span style='color:red'>Please enter your last name!</span>";
      errors[2] = "<span style='color:red'>Please enter your email!</span>";
      errors[3] = "<span style='color:red'>Please enter your user id!</span>";
      errors[4] = "<span style='color:red'>Please enter your password!</span>";
      errors[5] = "<span style='color:red'>Please confirm your password!</span>";
      for (i in inputs)
      {
        var errMessage = errors[i];
        var div = divs[i];
        if (inputs[i] == "")
        	document.getElementById(div).innerHTML = errMessage;
        else if (i==2)
        {
          var atpos=inputs[i].indexOf("@");
          var dotpos=inputs[i].lastIndexOf(".");
          if (atpos<1 || dotpos<atpos+2 || dotpos+2>=inputs[i].length)
        	document.getElementById('errEmail').innerHTML = "<span style='color: red'>Enter a valid email address!</span>";
          else
        	document.getElementById(div).innerHTML = "OK!";
        }
        else if (i==5)
        {
          var first = document.getElementById('password').value;
          var second = document.getElementById('confirm').value;
          if (second != first)
        	document.getElementById('errConfirm').innerHTML = "<span style='color: red'>Your passwords don't match!</span>";
          else
       		document.getElementById(div).innerHTML = "OK!";
        }
        else
        	document.getElementById(div).innerHTML = "OK!";
       }
     }
        function finalValidate()
        {
          var count = 0;
          for(i=0;i<6;i++)
          {
            var div = divs[i];
            if(document.getElementById(div).innerHTML == "OK!")
            count = count + 1;
          }
          if(count == 6)
          	document.getElementById("errFinal").innerHTML = "All the data you entered is correct!!!";
        }
   </script>
</head>
<body>
	<table id="table1">
      <tr>
        <td>First Name:</td>
        <td><input type="text" id="first" onkeyup="validate();" /></td>
        <td><div id="errFirst"></div></td>
      </tr>
      <tr>
        <td>Last Name:</td>
        <td><input type="text" id="last" onkeyup="validate();"/></td>
        <td><div id="errLast"></div></td>
      </tr>
      <tr>
        <td>Email:</td>
        <td><input type="text" id="email" onkeyup="validate();"/></td>
        <td><div id="errEmail"></div></td>
      </tr>
      <tr>
        <td>User Id:</td>
        <td><input type="text" id="uid" onkeyup="validate();"/></td>
        <td><div id="errUid"></div></td>
      </tr>
      <tr>
        <td>Password:</td>
        <td><input type="password" id="password" onkeyup="validate();"/></td>
        <td><div id="errPassword"></div></td>
      </tr>
      <tr>
        <td>Confirm Password:</td>
        <td><input type="password" id="confirm" onkeyup="validate();"/></td>
        <td><div id="errConfirm"></div></td>
      </tr>
      <tr>
        <td><input type="button" id="create" value="Create" onclick="validate();finalValidate();"/></td>
        <td><div id="errFinal"></div></td>
      </tr>
	</table>
</body>
</html>

Expected Behaviour:

Empty first name        -> Please enter your first name!
Email "ann@site"        -> Enter a valid email address!
Email "ann@site.com"    -> OK!
Passwords differ        -> Your passwords don't match!
All six fields valid    -> All the data you entered is correct!!!

Code explanation: Three arrays run in parallel. inputs holds the current values, errors holds the matching messages, and divs holds the id of the container that displays each message. The index therefore links a field, its error text, and its output location. The email branch accepts an address only when the at sign is not the first character, and when at least two characters separate the at sign from the final dot.

⚠️ Warning: Client-side validation improves the user experience but provides no security. Anyone can disable JavaScript or post directly to the endpoint, so every rule shown here must be repeated on the server.

Example#3: POPUP Message using Event

Display a simple message “Welcome!!!” on your demo webpage, and when the user hovers over the message a popup should be displayed with the message “Welcome to my WebPage!!!”.

Solution:

<html>
    <head>
        <title>Event!!!</title>
        <script type="text/javascript">
            function trigger() {
                document.getElementById("hover").addEventListener("mouseover", popup);
                function popup() {
                    alert("Welcome to my WebPage!!!");
                }
            }
        </script>
        <style>
            p{
                font-size: 50px;
                position: fixed;
                left: 550px;
                top: 300px;
            }
        </style>
    </head>
    <body onload="trigger();">
        <p id="hover">Welcome!!!</p>
    </body>
</html>

Expected Behaviour:

Page loads      -> the text "Welcome!!!" appears in large type
Mouse hovers    -> an alert box shows "Welcome to my WebPage!!!"

Code explanation: The listener is attached inside the trigger function, which runs on the body onload event. Waiting for load matters, because the paragraph with the id “hover” does not exist while the head is still being parsed. The same result is achieved more cleanly by placing the script just before the closing body tag, or by adding the defer attribute.

Example#4: Live Digital Clock using setInterval

Display the current time on the page and refresh it once every second. This example introduces timers and shows the modern alternative to document.write.

<html>
<head>
    <title>Digital Clock</title>
</head>
<body>
    <h2 id="clock">--:--:--</h2>

    <script>
        function showTime() {
            const now = new Date();
            const hh = String(now.getHours()).padStart(2, "0");
            const mm = String(now.getMinutes()).padStart(2, "0");
            const ss = String(now.getSeconds()).padStart(2, "0");

            // textContent is safer than innerHTML for plain text
            document.getElementById("clock").textContent = hh + ":" + mm + ":" + ss;
        }

        showTime();                 // draw immediately
        setInterval(showTime, 1000); // then refresh every second
    </script>
</body>
</html>

Expected Behaviour:

09:05:07
09:05:08
09:05:09   (the heading updates in place once per second)

Calling showTime once before setInterval avoids a visible one second delay when the page opens. Use clearInterval with the value returned by setInterval when the clock needs to stop.

Best Practices for Writing These JavaScript Examples

The three original examples date from an earlier style of JavaScript. The list below shows what to change when adapting them for production work.

  1. Replace document.write: It erases the whole document when called after the page has loaded. Build an element and set textContent or append a node instead.
  2. Declare every variable: Use let and const rather than relying on implicit globals such as the counter i in the loops above.
  3. Prefer textContent over innerHTML: Inserting user supplied text with innerHTML opens a cross-site scripting hole.
  4. Move handlers out of the markup: Replace onkeyup and onclick attributes with addEventListener, which keeps behaviour separate from structure.
  5. Convert prompt input: Wrap values in Number() before using them in comparisons, since prompt always returns a string.
  6. Validate again on the server: Treat browser checks as a convenience layer only.

To take these examples further, review JavaScript array methods for the parallel arrays used in the form validator, JavaScript strings for the email position checks, and cookies in JavaScript to remember the values a visitor entered. Decide where the finished script belongs by reading internal and external JavaScript.

FAQs

Save the code in a file with an .html extension and open it in any browser. No server, compiler, or library is required for any of the four examples on this page.

The while loop stops once j passes the column count. Without resetting j to 1, every row after the first would produce no cells at all.

No. It only improves the experience by giving instant feedback. A request can bypass the browser entirely, so the server must apply the same rules before storing anything.

Mouseover fires again when the pointer moves onto a child element, while mouseenter fires only once for the element itself. Choose mouseenter when repeated triggers are unwanted.

AI is useful for a first draft, but generated code frequently uses innerHTML with unescaped input. Read every line and replace unsafe DOM writes before publishing.

Yes, when you paste the exact console error alongside the code. Timing faults such as a script running before the element exists are among the easiest for an assistant to identify.

Summarize this post with: