Prompt Example

Live preview:

HTML:

<button id="btnPrompt" class="btn btn-info mr-2">Greet Me</button>
<div id="greeting" class="h5 mt-2"></div>

JavaScript:

// This example demonstrates how to use the prompt function to get user input
// and display a greeting message based on that input

//getElementById is used to select elements in this case a button with id "btnPrompt"
const button = document.getElementById("btnPrompt");

// querySelector is used to select elements in this case a button with id "greeting"
//# is used to select an element by its id #greeting
const greeting = document.querySelector("#greeting");

// greet is an event handler function that is called when the button is clicked
function greet() {
  //built-in prompt function is used to ask the user for their name
  const name = prompt("What is your name?");

  //textContent is used to set the text of the greeting element
  //template literals are used to create a string with embedded expressions
  //The backticks ` are used to create a template literal
  //${name} is used to insert the value of the name variable into the string
  greeting.textContent = `Hello ${name}, nice to see you!`;
}
// addEventListener is used to listen for click events on the button
// When the button is clicked, the greet function is called
button.addEventListener("click", greet);

Counter Example

Live preview:

HTML:

<button id="button_A" class="btn btn-success mr-2">Click me</button>
<span id="heading_A" class="h5"><!--some text will dynaically be inserted here--></span>

JavaScript:

// This example demonstrates how to create a button that counts the number of clicks
// and updates the text of a heading element with the number of clicks
        
// querySelector is used to select elements
// in this case a button with id "button_A" and a span with id "heading_A"
const buttonA = document.querySelector("#button_A");
const headingA = document.querySelector("#heading_A");

// count is a variable that keeps track of the number of clicks
let count = 1;

//onclick has an event handler, an arrow fuction that is triggered when the button is clicked
buttonA.addEventListener("click", () => {
    //textContent is used to set the text of the button and heading
    buttonA.textContent = "Try again!";
    headingA.textContent = `${count} clicks so far`;
    count += 1;
});

//traditional function
let hello = function(name) {
  return "Hello "+ name;
}

//hello rewritten as arrow function
//remove key word "function" and add arrow => , hence arrow function
hello = (name) => {
	return "Hello "+ name + " from arrow function"
}

//calls the arrow function "hello" with the argument "Anonymous". 
//and sets the text of the heading_A element
//why is the arrow function called here and not the traditional function?
document.querySelector("#heading_A").innerText=hello("Anonymous");

If-Else Example

Live preview:

The machine is stopped.

HTML:

<button id="machineBtn" class="btn btn-primary mr-2">Start machine</button>
<span id="machineStatus" class="h5">The machine is stopped.</span>

JavaScript:

// This example demonstrates how to toggle the state of a machine using a button
// The button text changes between "Start machine" and "Stop machine"

// Get DOM elements
const btn = document.querySelector("#machineBtn");
const txt = document.querySelector("#machineStatus");

// create my own eventhandler function updateBtn
// This function toggles the button text and status message
function updateBtn() {
    if (btn.textContent === "Start machine") {
        btn.textContent = "Stop machine";
        txt.textContent = "The machine has started!";
    } else {
        btn.textContent = "Start machine";
        txt.textContent = "The machine is stopped.";
    }
}

// Add an event listener to the button
// This listens for click events and calls the eventhandler, updateBtn, when clicked
btn.addEventListener("click", updateBtn);

Selecting Elements Example

Live preview:

HTML:

<select id="weatherSelect" class="form-select mb-3">
  <option value="">--Select Weather--</option>
  <option value="sunny">Sunny</option>
  <option value="rainy">Rainy</option>
  <option value="snowing">Snowing</option>
  <option value="overcast">Overcast</option>
</select>
<p id="weatherAdvice" class="h5"></p>

JavaScript:

// This example demonstrates how to use conditional logic to display different messages based on the selected weather condition
//querySelector is used to select elements in this case a select element with id "weatherSelect" and a paragraph with id "weatherAdvice"
const select = document.querySelector("#weatherSelect");
const para = document.querySelector("#weatherAdvice");

//change is an event that is triggered when the selected option in the dropdown changes
select.addEventListener("change", setWeather);

// setWeather is a function that updates the paragraph text based on the selected weather condition
// It is called when the change event occurs
function setWeather() {
  const choice = select.value;
  // === is a strict equality operator that checks both value and type
  if (choice === "sunny") {
    para.textContent = "It's sunny! Wear shorts and go to the beach!";
  } else if (choice === "rainy") {
    para.textContent = "Rain is falling - take an umbrella!";
  } else if (choice === "snowing") {
    para.textContent = "Snow is coming down - build a snowman!";
  } else if (choice === "overcast") {
    para.textContent = "Grey skies - take a rain coat just in case.";
  } else {
    para.textContent = "";
  }
}

Array looping

Live preview:

    HTML:

    <ul id="productList" class="list-group mb-3"></ul>
    <p id="totalPrice" class="h5"></p>

    JavaScript:

    // This example demonstrates how to process an array of products 
    // to show alla products and calculate the total price of all products
           
    // an array of products with their prices
    // Each product is a string in the format "Name:Price"
    const products = [
      'Underpants:6.99',
      'Socks:5.99',
      'T-shirt:14.99',
      'Trousers:31.99',
      'Shoes:23.99'
    ];
    
    const list = document.querySelector('#productList');
    const totalBox = document.querySelector('#totalPrice');
    let total = 0;
    
    //forEach is used to iterate over each element in this case a "product" in the products array
    // It takes a callback function, an arrow function that is executed for each product
    products.forEach((product) => {
      //split is used to separate the name and price of each product
      //The split method splits the string into an array using ':' as the delimiter
      const [name, price] = product.split(':');
      
      //Number is used to convert the price from a string to a number  
      total += Number(price);
      
      //createElement is used to create a new list item element, li tagg
      const listItem = document.createElement('li');
      
      //set the class name and text content of the list item
      listItem.className = 'list-group-item';//bootstarp class
      listItem.textContent = `${name} - ${price}`;
      
      //appendChild is used to add the list item to the unordered list
      list.appendChild(listItem);
    });
    
    //toFixed is used to format the total price to two decimal places
    totalBox.textContent = `Total: ${total.toFixed(2)}`;

    Array search

    Live preview:

    HTML:

    <div class="input-group mb-3">
      <input type="text" id="contactSearch" class="form-control" placeholder="Try  Mary, Chris, Bill or Sarah">
      <button id="searchBtn" class="btn btn-primary">Search</button>
    </div>
    <p id="searchResult" class="h5"></p>

    JavaScript:

    // This example demonstrates how to search for a phonenumber for a specific name.
    //allows users to find a phone number by entering a name
    
    // contacts is an array of strings, each containing a name and a phone number separated by a colon
    const contacts = [
      "Chris:2232322",
      "Sarah:3453456",
      "Bill:7654322",
      "Mary:9998769"
    ];
    
    const para = document.querySelector("#searchResult");
    const input = document.querySelector("#contactSearch");
    const btn = document.querySelector("#searchBtn");
    
    // addEventListener is used to listen for click events on elements like on this button
    // When the button is clicked, the arrow function inside is executed
    btn.addEventListener("click", () => {
      //toLowerCase is used to make the search case-insensitive
      //value is used to get user input from input field, 
      const searchName = input.value.toLowerCase();
      input.value = "";
      
      //focus is used to set the focus on the input field
      input.focus();
      para.textContent = "";
      
      //Examples of different for loops to iterate over arrays to find a phonenumber based on name
      //1. for...of loop is used to iterate over each contact(element) in the contacts array
      for (const contact of contacts) {
        const [name, phone] = contact.split(":");
        //toLowerCase is used to make the search case-insensitive
        if (name.toLowerCase() === searchName) {
          para.textContent = `${name}'s number is ${phone}`;
          break;
        }
      }
      
      //2. use of traditional index based for loop
      for (let i = 0; i < contacts.length; i++) {
        const [name, phone] = contacts[i].split(":");
        if (name.toLowerCase() === searchName) {
          para.textContent = `${name}'s number is ${phone}`;
          break;
        }
      }  
      
      if (para.textContent === "") {
        para.textContent = "Contact not found.";
      }
    });
    
    

    Array methods

    Live preview:

      HTML:

      <div class="input-group mb-3">
        <ul id="ulCarArrays"></ul>
      </div>
      

      JavaScript:

      // This example demonstrates various array methods in JavaScript
      // It includes filtering, mapping, finding, and sorting an array of car objects
      
      //cars is an array of car objects, each with properties like id, brand, model, year, price, and isElectric
      const cars = [
        { id: 1, brand: "Toyota", model: "Camry", year: 2020, price: 24000, isElectric: false },
        { id: 2, brand: "Tesla", model: "Model 3", year: 2022, price: 45000, isElectric: true },
        { id: 3, brand: "Ford", model: "Mustang", year: 2021, price: 38000, isElectric: false },
        { id: 4, brand: "BMW", model: "X5", year: 2023, price: 52000, isElectric: true },
        { id: 5, brand: "Honda", model: "Civic", year: 2019, price: 22000, isElectric: false },
      ];
      
      const ul = document.querySelector("#ulCarArrays");
      
      //"filter"  is used to create a new array with all elements that pass the test implemented by the provided arrow function
      // In this case, it filters out electric cars
      const electricCars = cars.filter(car => car.isElectric);
      //innerHTML is used to set the content of the unordered list
      //stringify is used to convert the array to a JSON string for display
      // The second parameter null, meanas no replacer function is need and the third parameter 2 are used to format the JSON string with indentation
      ul.innerHTML="<li>"+JSON.stringify(electricCars, null, 2)+"</li>"; // Output: as json the two Tesla & BMW (isElectric: true)
      
      //"map" is used to create a new array with the results of calling a provided arrow function on every element in the calling array
      // In this case, it extracts the model names of the cars
      const carModels = cars.map(car => car.model);
      ul.innerHTML+="<li>"+JSON.stringify(carModels, null, 2)+"</li>"; // Output: [ "Camry", "Model 3", "Mustang", "X5", "Civic" ]
      
      //"find" is used to find the first element in the array that satisfies the provided testing arrow function
      // In this case, it finds the car with id 3
      const carWithId3 = cars.find(car => car.id === 3);
      ul.innerHTML+="<li>"+JSON.stringify(carWithId3, null, 2)+"</li>"; // Output: { id: 3, brand: "Ford", model: "Mustang", year: 2021, price: 38000, isElectric: false }  
      
      //"sort" is used to sort the elements of an array in place and return the sorted array
      // In this case, it sorts the cars by price in ascending order  
      const sortedCars = cars.sort((carA, carB) => carA.price - carB.price);
      ul.innerHTML+="<li>"+JSON.stringify(sortedCars, null, 2)+"</li>"; // Output: sorted array of cars by price