Below is a set of JavaScript practical exercises designed to cover the full course content, progressing from simple to advanced concepts. These exercises align with the syllabus and focus on teaching JavaScript programming skills for web development. Each exercise includes a description, syllabus coverage (where applicable), aim, and JavaScript code.
Exercise 1: Basic JavaScript Syntax
Description : Write a JavaScript program that displays “Hello, World!” in the browser console and on a webpage.
Syllabus Coverage : Introduction to JavaScript, embedding scripts into web pages.
Aim : Introduce students to basic JavaScript syntax and its integration with HTML.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript Basics</title> </head> <body> <h1 id="output"></h1> <script> // Display in the browser console console.log("Hello, World!"); // Display on the webpage document.getElementById("output").innerText = "Hello, World!"; </script> </body> </html> |
Exercise 2: Variables and Data Types
Description : Write a JavaScript program that declares variables for a student’s name, age, and grade, and displays them on a webpage.
Syllabus Coverage : Primitive data types, variables.
Aim : Teach students how to declare and use variables in JavaScript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript Variables</title> </head> <body> <p id="student-info"></p> <script> let name = "Alice"; let age = 20; let grade = "A"; document.getElementById("student-info").innerHTML = `Name: ${name}<br>Age: ${age}<br>Grade: ${grade}`; </script> </body> </html> |
Exercise 3: Arrays
Description : Write a JavaScript program that creates an array of student names and displays them in a list format on a webpage.
Syllabus Coverage : Arrays.
Aim : Introduce students to arrays and their usage in JavaScript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript Arrays</title> </head> <body> <ul id="student-list"></ul> <script> const students = ["Alice", "Bob", "Charlie"]; const list = document.getElementById("student-list"); students.forEach(student => { const li = document.createElement("li"); li.textContent = student; list.appendChild(li); }); </script> </body> </html> |
Exercise 4: Control Structures
Description : Write a JavaScript program that checks if a number is even or odd and displays the result on a webpage.
Syllabus Coverage : Control structures (selection).
Aim : Teach students how to use conditional statements in JavaScript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript Control Structures</title> </head> <body> <p id="result"></p> <script> const number = 10; if (number % 2 === 0) { document.getElementById("result").innerText = `${number} is even.`; } else { document.getElementById("result").innerText = `${number} is odd.`; } </script> </body> </html> |
Exercise 5: Loops
Description : Write a JavaScript program that prints numbers from 1 to 10 using a loop and displays them on a webpage.
Syllabus Coverage : Control structures (repetition).
Aim : Teach students how to use loops in JavaScript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript Loops</title> </head> <body> <p id="numbers"></p> <script> let output = ""; for (let i = 1; i <= 10; i++) { output += i + " "; } document.getElementById("numbers").innerText = output; </script> </body> </html> |
Exercise 6: Functions
Description : Write a JavaScript program that defines a function to calculate the area of a rectangle and calls it with user-provided values.
Syllabus Coverage : Sub-programs (functions), parameter passing, return values.
Aim : Introduce students to writing reusable functions in JavaScript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript Functions</title> </head> <body> <p id="area"></p> <script> function calculateArea(length, width) { return length * width; } const length = 5; const width = 3; const area = calculateArea(length, width); document.getElementById("area").innerText = `The area of the rectangle is ${area}.`; </script> </body> </html> |
Exercise 7: Event Handling
Description : Write a JavaScript program that changes the background color of a webpage when a button is clicked.
Syllabus Coverage : Event handling.
Aim : Teach students how to handle user interactions using JavaScript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript Event Handling</title> </head> <body> <button id="change-color">Change Background Color</button> <script> document.getElementById("change-color").addEventListener("click", () => { document.body.style.backgroundColor = "lightblue"; }); </script> </body> </html> |
Exercise 8: DOM Manipulation
Description : Write a JavaScript program that dynamically adds a new paragraph to a webpage when a button is clicked.
Syllabus Coverage : DOM manipulation.
Aim : Teach students how to manipulate the Document Object Model (DOM).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript DOM Manipulation</title> </head> <body> <button id="add-paragraph">Add Paragraph</button> <div id="content"></div> <script> document.getElementById("add-paragraph").addEventListener("click", () => { const p = document.createElement("p"); p.textContent = "This is a new paragraph."; document.getElementById("content").appendChild(p); }); </script> </body> </html> |
Exercise 9: Forms and User Input
Description : Write a JavaScript program that collects user input from a form and displays it on the webpage.
Syllabus Coverage : Forms, input elements, GET/POST methods.
Aim : Teach students how to handle user input using forms in JavaScript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript Forms</title> </head> <body> <form id="user-form"> <label for="name">Enter your name:</label> <input type="text" id="name" name="name"> <button type="submit">Submit</button> </form> <p id="greeting"></p> <script> document.getElementById("user-form").addEventListener("submit", (event) => { event.preventDefault(); const name = document.getElementById("name").value; document.getElementById("greeting").innerText = `Hello, ${name}!`; }); </script> </body> </html> |
Exercise 10: Fetch API
Description : Write a JavaScript program that fetches data from a public API (e.g., JSONPlaceholder) and displays it on a webpage.
Syllabus Coverage : Advanced JavaScript concepts (API integration).
Aim : Introduce students to working with APIs and asynchronous programming.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript Fetch API</title> </head> <body> <h1>User List</h1> <ul id="user-list"></ul> <script> fetch('https://jsonplaceholder.typicode.com/users') .then(response => response.json()) .then(users => { const list = document.getElementById("user-list"); users.forEach(user => { const li = document.createElement("li"); li.textContent = user.name; list.appendChild(li); }); }) .catch(error => console.error('Error fetching data:', error)); </script> </body> </html> |
Exercise 11: Local Storage
Description : Write a JavaScript program that saves user preferences (e.g., theme color) to local storage and retrieves them when the page reloads.
Syllabus Coverage : Advanced JavaScript concepts (local storage).
Aim : Teach students how to persist data using local storage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript Local Storage</title> </head> <body> <button id="set-theme">Set Theme to Dark</button> <p id="theme-status"></p> <script> const themeStatus = document.getElementById("theme-status"); // Load saved theme const savedTheme = localStorage.getItem("theme"); if (savedTheme) { document.body.style.backgroundColor = savedTheme; themeStatus.innerText = `Current theme: ${savedTheme}`; } // Set theme document.getElementById("set-theme").addEventListener("click", () => { const theme = "darkblue"; document.body.style.backgroundColor = theme; localStorage.setItem("theme", theme); themeStatus.innerText = `Theme set to ${theme}`; }); </script> </body> </html> |
Exercise 12: Asynchronous Programming with Promises
Description : Write a JavaScript program that simulates an asynchronous task using Promises and displays the result.
Syllabus Coverage : Advanced JavaScript concepts (Promises).
Aim : Introduce students to asynchronous programming using Promises.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript Promises</title> </head> <body> <p id="output"></p> <script> function simulateAsyncTask() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("Task completed!"); }, 2000); }); } simulateAsyncTask() .then(result => { document.getElementById("output").innerText = result; }) .catch(error => { document.getElementById("output").innerText = `Error: ${error}`; }); </script> </body> </html> |
Exercise 13: Classes and Objects
Description : Write a JavaScript program that defines a class for a “Student” and creates objects to display student details.
Syllabus Coverage : Object-oriented programming (OOP).
Aim : Teach students how to use classes and objects in JavaScript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>JavaScript Classes</title> </head> <body> <p id="student-details"></p> <script> class Student { constructor(name, age, grade) { this.name = name; this.age = age; this.grade = grade; } getDetails() { return `Name: ${this.name}, Age: ${this.age}, Grade: ${this.grade}`; } } const student = new Student("Alice", 20, "A"); document.getElementById("student-details").innerText = student.getDetails(); </script> </body> </html> |
Above exercises comprehensively cover JavaScript-related topics, including variables , arrays , control structures , functions , event handling , DOM manipulation , forms , API integration , local storage , asynchronous programming , and OOP . They are designed to progressively build students’ skills while aligning with the learning outcomes.
Below are advanced JavaScript exercises that go beyond the syllabus, exploring modern and cutting-edge concepts in web development. These exercises will help you deepen your understanding of JavaScript and its capabilities in building dynamic, interactive, and scalable web applications.
Exercise 1: Asynchronous Programming with async/await
Description : Write a JavaScript program that uses async/await
to fetch data from an API and handle errors gracefully.
What You Learn : Modern asynchronous programming techniques using async/await
.
1 2 3 4 5 6 7 8 9 10 11 12 13 | // JavaScript Code async function fetchData() { try { const response = await fetch('https://jsonplaceholder.typicode.com/posts'); if (!response.ok) throw new Error('Network response was not ok'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } } fetchData(); |
Exercise 2: Modular JavaScript with ES6 Modules
Description : Create a modular JavaScript application using ES6 import
and export
.
What You Learn : Modularizing code for better organization and reusability.
File: math.js
1 2 3 4 5 6 7 8 | // math.js export function add(a, b) { return a + b; } export function subtract(a, b) { return a - b; } |
File: app.js
1 2 3 4 5 | // app.js import { add, subtract } from './math.js'; console.log(add(5, 3)); // Output: 8 console.log(subtract(10, 4)); // Output: 6 |
Exercise 3: Building a Custom JavaScript Library
Description : Create a small JavaScript library that provides utility functions like DOM manipulation, event handling, and AJAX requests.
What You Learn : Writing reusable libraries and encapsulating functionality.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // myLibrary.js const MyLibrary = (() => { const $ = (selector) => document.querySelector(selector); const on = (element, event, callback) => { element.addEventListener(event, callback); }; const ajax = async (url, method = 'GET', data = null) => { const options = { method, headers: { 'Content-Type': 'application/json' }, body: data ? JSON.stringify(data) : null, }; const response = await fetch(url, options); if (!response.ok) throw new Error('Request failed'); return response.json(); }; return { $, on, ajax }; })(); // Usage MyLibrary.$('#btn').addEventListener('click', () => { MyLibrary.ajax('https://jsonplaceholder.typicode.com/posts') .then(data => console.log(data)) .catch(err => console.error(err)); }); |
Exercise 4: Implementing a Publish-Subscribe Pattern
Description : Build a simple event bus using the publish-subscribe pattern to manage custom events.
What You Learn : Event-driven architecture and decoupling components.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // Event Bus class EventBus { constructor() { this.subscribers = {}; } subscribe(event, callback) { if (!this.subscribers[event]) this.subscribers[event] = []; this.subscribers[event].push(callback); } publish(event, data) { if (this.subscribers[event]) { this.subscribers[event].forEach(callback => callback(data)); } } } // Usage const bus = new EventBus(); bus.subscribe('message', (data) => console.log(`Received: ${data}`)); bus.publish('message', 'Hello, World!'); |
Exercise 5: Creating a Single Page Application (SPA) with JavaScript
Description : Build a simple SPA using JavaScript to handle routing without a framework.
What You Learn : Client-side routing and dynamic content loading.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <!-- HTML Code --> <!DOCTYPE html> <html> <head> <title>Simple SPA</title> </head> <body> <nav> <a href="#home">Home</a> <a href="#about">About</a> <a href="#contact">Contact</a> </nav> <div id="content"></div> <script> const routes = { '#home': '<h1>Welcome to Home</h1>', '#about': '<h1>About Us</h1>', '#contact': '<h1>Contact Us</h1>', }; window.addEventListener('hashchange', () => { const route = window.location.hash || '#home'; document.getElementById('content').innerHTML = routes[route] || '<h1>Page Not Found</h1>'; }); // Initial load window.dispatchEvent(new HashChangeEvent('hashchange')); </script> </body> </html> |
Exercise 6: Working with Web Workers
Description : Use Web Workers to perform heavy computations without blocking the main thread.
What You Learn : Offloading tasks to background threads for better performance.
File: worker.js
1 2 3 4 5 | // worker.js self.onmessage = (event) => { const result = event.data * 2; self.postMessage(result); }; |
File: main.js
1 2 3 4 5 6 7 8 | // main.js const worker = new Worker('worker.js'); worker.postMessage(10); worker.onmessage = (event) => { console.log(`Result from worker: ${event.data}`); }; |
1 |
Exercise 7: Building a Real-Time Chat Application with WebSocket
Description : Create a real-time chat application using WebSocket for instant communication.
What You Learn : Real-time communication and WebSocket protocol.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // Server (Node.js with WebSocket) const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { ws.on('message', (message) => { wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(message); } }); }); }); // Client (JavaScript) const socket = new WebSocket('ws://localhost:8080'); socket.onopen = () => { console.log('Connected to server'); socket.send('Hello, Server!'); }; socket.onmessage = (event) => { console.log(`Message from server: ${event.data}`); }; |
Exercise 8: Using Proxies for Object Observation
Description : Use JavaScript Proxies to observe changes to an object’s properties.
What You Learn : Advanced object manipulation and reactive programming concepts.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // JavaScript Code const handler = { get(target, prop) { console.log(`Accessed property: ${prop}`); return target[prop]; }, set(target, prop, value) { console.log(`Updated property: ${prop} with value: ${value}`); target[prop] = value; return true; }, }; const user = new Proxy({ name: 'Alice', age: 25 }, handler); console.log(user.name); // Accessed property: name user.age = 30; // Updated property: age with value: 30 |
Exercise 9: Implementing a Virtual DOM
Description : Build a simplified version of a virtual DOM to understand how frameworks like React work under the hood.
What You Learn : Efficient DOM updates and diffing algorithms.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // Virtual DOM Implementation function createElement(tag, props, ...children) { return { tag, props, children }; } function render(vdom) { const element = document.createElement(vdom.tag); for (const [key, value] of Object.entries(vdom.props || {})) { element.setAttribute(key, value); } vdom.children.forEach(child => { if (typeof child === 'string') { element.appendChild(document.createTextNode(child)); } else { element.appendChild(render(child)); } }); return element; } // Usage const vdom = createElement('div', { id: 'root' }, createElement('h1', {}, 'Hello, Virtual DOM'), createElement('p', {}, 'This is a paragraph.') ); document.body.appendChild(render(vdom)); |
Exercise 10: Using Generators for Iteration
Description : Write a JavaScript program that uses generators to create an infinite sequence of numbers.
What You Learn : Lazy evaluation and generator functions.
1 2 3 4 5 6 7 8 9 10 11 12 | // JavaScript Code function* generateNumbers() { let num = 1; while (true) { yield num++; } } const generator = generateNumbers(); console.log(generator.next().value); // 1 console.log(generator.next().value); // 2 console.log(generator.next().value); // 3 |
Exercise 11: Building a Custom Promise Implementation
Description : Implement a simplified version of JavaScript Promises from scratch.
What You Learn : Understanding Promises and their internal mechanics.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | // Custom Promise Implementation class MyPromise { constructor(executor) { this.state = 'pending'; this.value = undefined; this.handlers = []; const resolve = (value) => { if (this.state !== 'pending') return; this.state = 'fulfilled'; this.value = value; this.handlers.forEach(({ onFulfilled }) => onFulfilled(value)); }; const reject = (error) => { if (this.state !== 'pending') return; this.state = 'rejected'; this.value = error; this.handlers.forEach(({ onRejected }) => onRejected(error)); }; executor(resolve, reject); } then(onFulfilled, onRejected) { return new MyPromise((resolve, reject) => { const handle = () => { try { const result = onFulfilled(this.value); resolve(result); } catch (error) { reject(error); } }; if (this.state === 'fulfilled') { handle(); } else { this.handlers.push({ onFulfilled: handle }); } }); } } // Usage new MyPromise((resolve) => resolve('Success')) .then((result) => console.log(result)); |
Exercise 12: Using Intersection Observer for Lazy Loading
Description : Implement lazy loading of images using the Intersection Observer API.
What You Learn : Efficient resource loading and performance optimization.
1 2 3 4 5 6 7 8 9 10 11 12 | // JavaScript Code document.querySelectorAll('img[data-src]').forEach(img => { const observer = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { img.src = img.dataset.src; observer.unobserve(img); } }); }); observer.observe(img); }); |
These exercises explore advanced JavaScript concepts such as asynchronous programming , modularization , custom libraries , publish-subscribe patterns , SPAs , Web Workers , Proxies , virtual DOM , generators , custom promises , and lazy loading . They provide practical, real-world applications of JavaScript and will help you explore areas beyond the syllabus.