JavaScript Examples [51 Useful Examples]

JavaScript is powerful for web developers, offering countless ways to enhance website functionality. It provides the building blocks for modern web applications, from handling simple arithmetic operations to creating complex interactive elements. These practical examples can help you learn the fundamentals of variables, operators, loops, and other essential JavaScript concepts.

As a JavaScript developer, you should be familiar with its core features, such as arithmetic operators (addition, subtraction, multiplication, division), variables, output methods, and commenting techniques.

Table of Contents:

What is JavaScript?

JavaScript is a lightweight, object-based scripting language that adds functionality to HTML code. It makes web pages interactive, allowing users to engage with content dynamically.

This versatile language serves multiple purposes. Developers use JavaScript for:

  • Game development
  • Mobile app creation
  • Making HTML forms dynamic
  • Building client-side dynamic pages

One major benefit of JavaScript is its universal browser compatibility. All major browsers support it, including:

  • Chrome
  • Firefox
  • Edge
  • Safari
  • Opera

JavaScript runs on any operating system, including Windows, Linux, and Mac. To use JavaScript, developers simply add code within <script> tags in an HTML file. When the browser loads the HTML, it automatically runs the JavaScript code.

With features like let introduced in ECMAScript 2015 (ES6), JavaScript continues to evolve as a powerful tool for web development.

Check out How to Check Which Radio Button is Selected Using jQuery?

Editors For JavaScript

Choosing the right editor can improve your coding experience when working with JavaScript. Several popular options exist:

  • VS Code – Feature-rich with excellent extensions
  • Sublime Text – Fast and lightweight
  • Atom – Highly customizable
  • Notepad++ – Simple but effective
  • Komodo Edit – Good for beginners

These editors offer syntax highlighting, code completion, and debugging tools that make JavaScript development easier and more efficient.

How to Start with JavaScript?

JavaScript adds interactivity to websites. To begin coding in JavaScript, you need to understand a few basic principles.

You must place JavaScript code between <script> and </script> tags in your HTML document. These scripts can go in either the <head> or <body> section, or both. Here’s a simple example:

<script>
  alert("Hello, welcome to JavaScript!");
</script>

There are two main ways to include JavaScript in your webpage:

  1. Directly in HTML – Writing code between script tags
  2. External files – Storing code in separate .js files

Using external files is often better for organization. To link an external JavaScript file:

<script src="yourFileName.js"></script>

You can create interactive elements like buttons that trigger JavaScript functions:

<button onclick="showMessage()">Click Me</button>

The function showMessage() would be defined in your JavaScript code to perform a specific action when the button is clicked.

For beginners, start with simple tasks like displaying alerts or changing text content before moving to more complex projects.

JavaScript Examples

Check out Execute Functions After Page Load Using jQuery

Now, let me show you the 51 useful examples of JavaScript.

Example-1: Display Alert in JavaScript

JavaScript offers several ways to create pop-up dialog boxes to interact with users. These dialog boxes help show messages, get confirmations, or collect user input while browsing your website.

Display Alert Box Using JavaScript

The alert box is the simplest dialog box in JavaScript. It shows a message and has an OK button to close it.

function showAlert() {
  alert("Created Account");
}

When this function runs, a small box appears on screen with the message “Created Account” and an OK button. Users must click OK to continue using the page.

You can add line breaks in your alert messages using the \n character:

alert("Hello\nHow are you?");

This creates an alert with text on two lines.

A basic example of an alert in a form:

<input type="text" id="txtFirstName" name="firstname">
<input type="text" id="txtLastName" name="lastname">
<button onclick="showAlert()">Submit</button>

When users click Submit, they’ll see the alert message.

Display Confirmation Box Using JavaScript

A confirmation box asks users to verify or accept something. It displays both OK and Cancel buttons.

function showConfirmationMessage() {
  var result = confirm("Do you want to use this account?");
  
  if (result == true) {
    alert("Account created successfully");
  } else {
    alert("Sorry, try again. Your account was not created");
  }
}

The confirm() function returns:

  • true if the user clicks OK
  • false if the user clicks Cancel

This is useful when you need users to verify actions before proceeding.

Display Prompt Box Using JavaScript

The prompt box collects text input from users through a dialog box.

function showPromptBox() {
  var username = prompt("Please enter your username", "");
  var message;
  
  if (username == null || username == "") {
    message = "User cancelled the prompt.";
  } else {
    message = "Hello " + username + "! Welcome to your SharePoint site";
  }
  
  document.getElementById("messageArea").innerHTML = message;
}

The prompt function takes two parameters:

  • The message to display
  • A default value for the input field (can be empty)

This dialog box includes a text input field, an OK button, and a Cancel button.

Read Handle Dropdown Change Event in jQuery

Example-2: Mouse Movement Events in JavaScript

JavaScript offers powerful events that respond to mouse movements. Two key events are onmouseover and onmouseout. These events trigger functions when a user’s mouse enters or leaves an element.

Here’s how they work:

  • onmouseover: Fires when a mouse pointer moves onto an element
  • onmouseout: Fires when a mouse pointer moves away from an element

You can use these events to create interactive image effects. For example:

function makeImageLarger(image) {
  image.style.height = "64px";
  image.style.width = "64px";
}

function makeImageSmaller(image) {
  image.style.height = "32px";
  image.style.width = "32px";
}

To implement these functions, add the events directly to your HTML:

<img onmouseover="makeImageLarger(this)" 
     onmouseout="makeImageSmaller(this)"
     src="image.jpg" width="32" height="32">

You can reverse these effects by swapping the events. This creates the opposite effect, where images shrink on hover and enlarge when the mouse leaves.

These mouse events pair well with onclick for creating fully interactive elements that respond to different types of user interactions.

Read How to Check if a Checkbox is Checked Using jQuery

Example-3: Using JavaScript for Key Press Alerts

JavaScript can create alert messages when users press keys in text boxes. To implement this function, add an event listener to your input element.

<!DOCTYPE html>
<html>
<body>
  <p><b>Key Press Alert Example</b></p>
  <input type="text" id="textInput" onkeypress="showAlert()">
  
  <script>
    function showAlert() {
      alert("You pressed a key in the text box!");
    }
  </script>
</body>
</html>

This code creates a simple text box that displays an alert whenever any key is pressed within it.

Example-4: JavaScript Form Validation Examples

Here are some form validation examples of JavaScript.

Empty Field Check

JavaScript makes it easy to check if users have filled out required fields. This simple validation stops form submission when important information is missing.

function checkRequired() {
  if(document.getElementById('nameField').value.trim() == "") {
    alert('Please fill out this field');
    nameField.focus();
    return false;
  }
  alert("Form submitted successfully");
  return true;
}

This code checks if a text field is empty when the user clicks submit. If it’s empty, an alert