Digital Clock

<!DOCTYPE html>
<html>
<head>
  <title>Digital Clock</title>
</head>
<body>

  <!-- Heading to display time -->
  <h1 id="clock"></h1>

  <!-- Link JavaScript file -->
  <script src="script.js"></script>

</body>
</html>
// Function to display current time
function showTime() {

  // Create a Date object
  let time = new Date();

  // Get hours from time
  let hours = time.getHours();

  // Get minutes from time
  let minutes = time.getMinutes();

  // Get seconds from time
  let seconds = time.getSeconds();

  // Add 0 before single digit numbers
  if (hours < 10) hours = "0" + hours;
  if (minutes < 10) minutes = "0" + minutes;
  if (seconds < 10) seconds = "0" + seconds;

  // Display time in HH:MM:SS format
  document.getElementById("clock").innerText =
    hours + ":" + minutes + ":" + seconds;
}

// Call function every 1 second
setInterval(showTime, 1000);

Counter App In JavaScript

This counter app works by first displaying a number inside an <h1> element, which starts at 0, and storing that value in a JavaScript variable called count. When you click any button, it calls a specific JavaScript function using the onclick attribute. The Increase button runs the increase() function, which adds 1 to the count variable and then updates the displayed number by selecting the <h1> element using document.getElementById("count") and changing its innerText. The Decrease button works the same way but subtracts 1 from count using the decrease() function. The Reset button calls the reset() function, which sets count back to 0 and updates the display again. In short, the logic is: store a value in a variable, change that value when a button is clicked, and immediately reflect the new value on the webpage using DOM manipulation.

<!DOCTYPE html>
<html>
<head>
  <title>Counter App</title>
</head>
<body>

  <!-- Heading to show the counter value -->
  <h1 id="count">0</h1>

  <!-- Button to increase count -->
  <button onclick="increase()">Increase</button>

  <!-- Button to decrease count -->
  <button onclick="decrease()">Decrease</button>

  <!-- Button to reset count -->
  <button onclick="reset()">Reset</button>

  <!-- Link JavaScript file -->
  <script src="script.js"></script>

</body>
</html>
// Create a variable to store count value
let count = 0;

// Function to increase the count
function increase() {
  count = count + 1;               // Add 1 to count
  document.getElementById("count").innerText = count; // Update text
}

// Function to decrease the count
function decrease() {
  count = count - 1;               // Subtract 1 from count
  document.getElementById("count").innerText = count; // Update text
}

// Function to reset the count
function reset() {
  count = 0;                       // Set count back to 0
  document.getElementById("count").innerText = count; // Update text
}

Add To Cart Example In JavaScript

<!DOCTYPE html>
<html>
<head>
  <title>Simple JS Cart</title>
</head>
<body>

<h2>Products</h2>
<div>
  <button onclick="addToCart('Apple', 1.00)">Add Apple ($1)</button>
  <button onclick="addToCart('Banana', 0.50)">Add Banana ($0.50)</button>
  <button onclick="addToCart('Orange', 0.80)">Add Orange ($0.80)</button>
</div>

<h2>Your Cart</h2>
<ul id="cart-list"></ul>
<p><strong>Total: $<span id="total">0.00</span></strong></p>

<script src="cart.js"></script>
</body>
</html>
// Create an empty array to store cart items
let cart = [];

// Function that runs when a product is added to the cart
function addToCart(name, price) {

  // Search the cart for an item with the same name
  // `i` represents each item while looping through the array
  const item = cart.find(i => i.name === name);

  // If the item already exists in the cart
  if (item) {
    // Increase its quantity by 1
    item.qty++;
  } else {
    // Otherwise, add a brand new item object to the cart
    cart.push({ name, price, qty: 1 });
  }

  // Update the cart display on the webpage
  updateCart();
}

// Function to refresh and show the current cart items
function updateCart() {

  // Get the HTML <ul> element where items will be displayed
  const list = document.getElementById("cart-list");

  // Get the HTML <span> where the total price will appear
  const totalEl = document.getElementById("total");

  // Clear the previous cart display
  list.innerHTML = "";

  // Start total price at 0
  let total = 0;

  // Loop through all items in the cart
  cart.forEach(item => {

    // Add this item's total cost (price × quantity) to the total
    total += item.price * item.qty;

    // Create a new list item <li> for this cart entry
    const li = document.createElement("li");

    // Set the text, e.g. "Apple x 2 - $2.00"
    li.textContent = `${item.name} x ${item.qty} - $${(item.price * item.qty).toFixed(2)}`;

    // Add this <li> to the <ul> list
    list.appendChild(li);
  });

  // Update the total price on screen
  totalEl.textContent = total.toFixed(2);
}

Student registers using a form in JavaScript

This code creates a simple student registration system using an HTML form and JavaScript. When the user submits the form, JavaScript prevents the page from reloading, collects the entered name, email, and course, and stores each student as an object inside an array. The array is saved in localStorage, so the list of registered students remains even after the page is refreshed. Each time a student is added, the updated list is displayed on the page by looping through the array and printing each student’s information. This allows multiple students to be registered, stored permanently in the browser, and shown as a list.

<!DOCTYPE html>
<html>
<head>
    <title>Student Registration</title>
</head>
<body>

<h2>Student Registration Form</h2>

<form id="studentForm">
    <label>Name:</label><br>
    <input type="text" id="name" required><br><br>

    <label>Email:</label><br>
    <input type="email" id="email" required><br><br>

    <label>Course:</label><br>
    <input type="text" id="course" required><br><br>

    <button type="submit">Register</button>
</form>

<h3>Registered Students:</h3>
<ul id="studentList"></ul>

<script src="script.js"></script>
</body>
</html>
let students = [];  // Array to store all registered students

document.getElementById("studentForm").addEventListener("submit", function(event) {
    event.preventDefault();

    // Create student object
    const student = {
        name: document.getElementById("name").value,
        email: document.getElementById("email").value,
        course: document.getElementById("course").value
    };

    // Add student to array
    students.push(student);

    // Display student list
    displayStudents();

    // Clear form
    this.reset();
});

function displayStudents() {
    const list = document.getElementById("studentList");
    list.innerHTML = ""; // Clear list before updating

    students.forEach((student, index) => {
        list.innerHTML += `<li>${index + 1}. ${student.name} - ${student.email} - ${student.course}</li>`;
    });
}

Student Grading Form Example In JavaScript

<!DOCTYPE html> <!-- Tells the browser this is an HTML5 document -->
<html>
<head>
    <title>Student Grading System</title> <!-- Title of the webpage -->
</head>
<body>

<h2>Student Grading Form</h2> <!-- Heading displayed on the page -->

<!-- The form where user inputs student data -->
<form id="gradeForm">
    <!-- Input for student name -->
    <label>Student Name:</label><br>
    <input type="text" id="name" required><br><br>

    <!-- Input for student ID -->
    <label>Student ID:</label><br>
    <input type="text" id="studentId" required><br><br>

    <!-- Input for score (0–100) -->
    <label>Score:</label><br>
    <input type="number" id="score" min="0" max="100" required><br><br>

    <!-- Button the user clicks to calculate grade -->
    <button type="button" onclick="calculateGrade()">Submit</button>
</form>

<!-- Area where the result will be shown -->
<h3>Result:</h3>
<div id="result"></div>

<script>
// This function runs when the "Submit" button is clicked
function calculateGrade() {

    // Get the value of the "name" input field
    let name = document.getElementById("name").value;

    // Get the value of the "studentId" input field
    let studentId = document.getElementById("studentId").value;

    // Get the numeric value of the "score" input field
    let score = Number(document.getElementById("score").value);

    // Variable to store the grade
    let grade;

    // Check score and assign the correct grade
    if (score >= 90) grade = "A";        // Score 90–100
    else if (score >= 80) grade = "B";   // Score 80–89
    else if (score >= 70) grade = "C";   // Score 70–79
    else if (score >= 60) grade = "D";   // Score 60–69
    else grade = "F";                    // Score below 60

    // Display all results inside the "result" div
    document.getElementById("result").innerHTML = `
        <p><strong>Name:</strong> ${name}</p>
        <p><strong>ID:</strong> ${studentId}</p>
        <p><strong>Score:</strong> ${score}</p>
        <p><strong>Grade:</strong> ${grade}</p>
    `;
}
</script>

</body>
</html>

Simple Calculator Example in JavaScript

<head>
  <title>Simple Calculator</title>
</head>
<body>
  <h2>Calculator</h2>

  <input id="num1" type="number" placeholder="Number 1">
  <input id="num2" type="number" placeholder="Number 2">

  <select id="operator">
    <option value="+">+</option>
    <option value="-">-</option>
    <option value="*">*</option>
    <option value="/">/</option>
  </select>

  <button onclick="calculate()">Calculate</button>

  <p id="result"></p>

  <script>
    function calculate() {
      const num1 = parseFloat(document.getElementById("num1").value);
      const num2 = parseFloat(document.getElementById("num2").value);
      const op = document.getElementById("operator").value;
      let result;

      switch (op) {
        case '+': result = num1 + num2; break;
        case '-': result = num1 - num2; break;
        case '*': result = num1 * num2; break;
        case '/': result = num2 !== 0 ? num1 / num2 : "Error: Divide by zero"; break;
        default: result = "Invalid operator";
      }

      document.getElementById("result").innerText = "Result: " + result;
    }
  </script>
</body>
</html>

Java Script Exam 3

4. What does Math.max(20,25,-30) return?



5. Which function is used if two have the same name?


Cheat Sheet

JavaScript Master Cheat Sheet

A compact, styled reference that covers basics → advanced topics. Paste into a WordPress Custom HTML block.

Basics

Include scripts, comments, and simple examples.

<!-- Inline -->
<script>
  // JS goes here
  console.log('Hello world');
</script>

<!-- External file -->
<script src="app.js"></script>

Variables & Types

Use let/const for block scope; var is function-scoped.

// Declaration examples
var legacy = 'hello';
let counter = 0;
const PI = 3.14159;

// Common types
let name = "Jane";           // string
let isActive = true;         // boolean
let scores = [10, 20, 30];   // array
let user = { id: 1, name: 'J' }; // object

Arrays

Common methods for manipulating arrays.

const fruits = ["Banana","Apple","Pear"];
fruits.push("Orange");          // add
fruits.pop();                   // remove last
fruits.includes("Apple");       // true
const part = fruits.slice(1,3); // shallow copy portion
fruits.splice(2,1, "Kiwi");     // remove & replace

Operators

Arithmetic, comparison, logical.

5 + 3;   // 8
10 % 3;    // 1 remainder
x === y;   // strict equality
x !== y;   // not equal
a && b;    // logical AND
a || b;    // logical OR
!flag;     // logical NOT

Functions

Classic, arrow, default params, IIFE.

// Classic
function greet(name){ return `Hello ${name}`; }

// Arrow
const add = (a,b) => a + b;

// Default param
function welcome(user = 'Guest'){ console.log(user); }

// IIFE (immediately-invoked)
(function(){ console.log('Init'); })();

Loops

for, while, for…of, break/continue.

// for
for(let i=0;i<5;i++){ console.log(i); }

// while
let n=3; while(n--){console.log(n);}

// for...of for arrays
for(const v of [1,2,3]) { console.log(v); }

// break & continue
for(let i=0;i<5;i++){
  if(i===2) continue;
  if(i===4) break;
}

If / Else

Conditional logic with ternary shortcuts.

if(age >= 18){
  console.log('Adult');
} else if(age >= 13){
  console.log('Teen');
} else {
  console.log('Child');
}

// ternary
const status = age >= 18 ? 'Adult' : 'Minor';

Strings

Common methods & escape sequences.

const s = "JavaScript";
s.toLowerCase();
s.toUpperCase();
s.includes("Script");
s.replace("Java","ECMA");
s.slice(0,4);   // "Java"
// escapes: \n, \t, \', \"

Regular Expressions

Patterns, flags, common usage.

// flags: i (ignore), g (global), m (multiline)
const rx = /\\d+/g;
"abc123".match(rx);       // ["123"]
/^[A-Z]/.test("Hello");   // true if starts with capital

Numbers & Math

Parsing, Math helper methods.

Number("42");      // 42
parseInt("10px");    // 10
parseFloat("3.14");  // 3.14

Math.random();       // 0..1
Math.round(2.7);     // 3
Math.max(1,5,3);     // 5
Math.sqrt(16);       // 4

Dates

Create and manipulate dates.

const now = new Date();
const custom = new Date(2025, 11, 25); // year, monthIndex(0-11), day
now.getFullYear();
now.getMonth();    // 0-11
now.getTime();     // ms since 1970

DOM (Document)

Select elements, update content, create nodes.

// Select
const el = document.getElementById('title');
const firstBtn = document.querySelector('.btn');

// Update
el.textContent = 'New Title';
el.innerHTML = '<strong>Bold</strong>';

// Create / append
const div = document.createElement('div');
div.textContent = 'Hi';
document.body.appendChild(div);

Browser & Window

Window methods & properties.

alert('Hi');
console.log(window.location.href);
setTimeout(()=>console.log('later'), 1000);
localStorage.setItem('k','v');

Events

Listening patterns and common event names.

// Click
button.addEventListener('click', (e) => {
  console.log('clicked', e.target);
});

// Keyboard
window.addEventListener('keydown', (e) => {
  if(e.key === 'Enter') console.log('enter pressed');
});

Errors & Debugging

try/catch and useful console tools.

try {
  mightFail();
} catch(err) {
  console.error('Error:', err.message);
} finally {
  console.log('cleanup');
}

// console methods: log, warn, error, table, group

Tip: Use the copy buttons to quickly paste examples into your editor.

Java Script Exam 2

1. What keyword creates a block-scoped variable that can be reassigned?

let score = 10;

2. Which statement correctly creates a function named sum?

function sum(a, b) { return a + b; }

3. What will this log?

console.log(typeof null);

4. Which method adds a value to the end of an array?

let a = [1,2]; a.push(3);

5. What does === test for?

6. Which of these creates an object with a property name?

let obj = { name: 'Sam' };

7. What will [1,2,3].map(x => x * 2) return?

[1,2,3].map(x => x * 2);

8. Which is true about const?

9. What is hoisting in JavaScript?

10. Which method parses a JSON string into an object?

JSON.parse('{"a":1}');

11. What will this expression return: [...'abc'] ?

[...'abc']

12. How do you schedule a function to run after 2 seconds?

setTimeout(fn, 2000);

13. Which event fires when the DOM has been loaded (but before images load)?

14. What does Array.prototype.filter return?

15. Which of these accesses the element with id ‘app’?

document.getElementById('app')

16. What is a Promise?

17. How do you catch errors from a Promise?

promise.then(...).catch(err => ...)

18. What does async/await provide?

19. Which built-in method returns the characters in a string as uppercase?

'hi'.toUpperCase()

20. How do you remove the first element from an array?

let a = [1,2,3]; a.shift();

21. Which operator spreads an array into separate arguments?

Math.max(...[1,2,3])

22. What will 0 == '0' evaluate to?

23. Which method trims whitespace from both ends of a string?

'  hi  '.trim()

24. What will typeof [] return?

25. Which regex flag makes matching case-insensitive?

/abc/i

26. Which built-in object provides methods for rounding and generating random numbers?

27. What is the output of typeof NaN?

28. Which DOM API finds elements by class name?

document.getElementsByClassName('btn')

29. What does event.preventDefault() do?

30. Which of these creates a shallow copy of an object?

let copy = Object.assign({}, obj);

31. What does document.createElement('div') do?

32. Which method returns the index of the first match in an array?

33. Which will parse integer from string?

34. Which of the following is a truthy value?

35. What does Object.keys(obj) return?

36. Which will stop propagation of an event so it doesn’t bubble up?

37. Which creates a new object that delegates to a specified prototype?

38. Which will convert a value to a number, returning NaN on failure?

39. What will 0 === -0 evaluate to?

40. Which statement throws an exception?

41. Which returns milliseconds since 1970-01-01 UTC?

42. What does call() do on functions?

43. Which removes a property from an object?

delete obj.prop;

44. Which is true about arrow functions?

45. What is event delegation?

46. Which array method reduces values to a single value?

47. What does void 0 evaluate to?

48. Which error type indicates invalid JSON or code syntax?

49. Which returns true if at least one element passes a predicate?

arr.some(x => x > 5)

50. Which method adds an element as the last child of a node?

parent.appendChild(child)

JavaScript Exam 1

1. What keyword creates a changeable variable?




2. What is the boolean value of the string “0”?

Boolean("0")



3. What is the length of this array?

let arr = ["x", "y", "z"];



4. What does a function return if it has no return statement?




5. Can JavaScript be included in any valid HTML file?




6. What will this display?

let x = 4; let y = 6; let z = x + "" + y; alert(z);



7. Will this behave the same in all browsers?

"hello".substring(-1);



8. What does parseInt return here?

parseInt(52.9);



9. Can browser JavaScript directly read/write arbitrary local files?




10. What will this loop alert?

let total=0; for(let i=1;i<=8;i++){ if(i%3===0) continue; if(i>5) break; total+=i } alert(total);



12. Do all JavaScript engines behave identically for every feature?




13. What is the result of “super”+”man”?




14. What does s.replace(/l/g,”#”) do to “balloon”?




15. What does s.replace(“l”,”#”) do to “balloon”?




16. Which returns the integer part of a number?

Math.floor(3.9)



17. What will this alert?

let a=4, b=2; function calc(x){ b = a + x; return ++b; } alert(calc(3));



18. How to append 5 to array nums?




19. Which event fires when the mouse enters an element?




20. typeof Infinity returns?




21. Which keyword declares a constant?




22. What does Number(“123”) return?




23. What does console.log(“5” – 2) output?




24. What is the result of [] + [] ?




25. typeof [] returns?




26. Which method removes the last item of an array?




27. What value does let x; create?




28. What does “hello”.toUpperCase() return?




29. Which operator checks both value and type?




30. What does “cat”.includes(“a”) return?




31. What does typeof null return?




32. What does !true evaluate to?




33. Which literal creates an array?




34. What does push() return?




35. Which loop runs the body at least once?




36. Which event triggers on a click?




37. What is the result of NaN === NaN ?




38. Which is a primitive type?




39. typeof function(){} returns?




40. What does JSON.stringify({a:1}) do?




41. Which method adds elements to the start of an array?




42. What does “10” + 1 produce?




43. How to make a shallow copy of array a?




44. Which checks array membership?




45. typeof (function(){}) returns?




46. Which method converts a string to lowercase?




47. What does 0 == “0” evaluate to?




48. Which declares a block-scoped variable?




49. Which method splits a string into an array?




50. Which array method returns true if every element passes the test?