JavaScript & Web Dev
Complete Programs Study Guide — FULL CODE
All 24 Programs | Exam Ready | HTML + JS + React + Node + XML
Every program is COMPLETE — ready to copy into exam answer sheet. HTML programs include full <!DOCTYPE
html> structure. Node/React programs include all imports and setup.
■ SECTION 1 — JavaScript Core (Programs 1–11)
Program 1: Validate Username & Password
Username: alphanumeric 5–15 chars | Password: min 8 chars, uppercase, lowercase, number.
<!DOCTYPE html>
<html>
<head><title>Validate Username & Password</title></head>
<body>
<h2>User Validation Form</h2>
Username: <input type='text' id='user' /><br/><br/>
Password: <input type='password' id='pass' /><br/><br/>
<button onclick='validate()'>Validate</button>
<script>
function validate() {
var user = [Link]('user').value;
var pass = [Link]('pass').value;
// Username: only letters & digits, 5 to 15 characters
var userPattern = /^[a-zA-Z0-9]{5,15}$/;
if () {
alert('Username must be 5-15 alphanumeric characters!');
return;
}
if ([Link] < 8) {
alert('Password must be at least 8 characters!');
return;
}
if (!/[A-Z]/.test(pass)) {
alert('Password must contain at least one uppercase letter!');
return;
}
if (!/[a-z]/.test(pass)) {
alert('Password must contain at least one lowercase letter!');
return;
}
if (!/[0-9]/.test(pass)) {
alert('Password must contain at least one number!');
return;
}
alert('Username and Password are valid!');
}
</script>
</body>
</html>
Program 2: Validate Email
Email must contain '@' and '.' characters.
<!DOCTYPE html>
<html>
<head><title>Email Validation</title></head>
<body>
<h2>Email Validation</h2>
Email: <input type='text' id='email' /><br/><br/>
<button onclick='validateEmail()'>Check Email</button>
<script>
function validateEmail() {
var email = [Link]('email').value;
if ([Link]('@') == -1 || [Link]('.') == -1) {
alert('Invalid email! Email must contain @ and .');
} else {
alert('Email is valid!');
}
}
</script>
</body>
</html>
Program 3: Full Form Validation – Username + Password + Email
Combined validation: all fields required, password min 8 chars, valid email.
<!DOCTYPE html>
<html>
<head><title>Full Form Validation</title></head>
<body>
<h2>Signup Form</h2>
Username: <input type='text' id='user' /><br/><br/>
Password: <input type='password' id='pass' /><br/><br/>
Email: <input type='text' id='email' /><br/><br/>
<button onclick='validateForm()'>Submit</button>
<script>
function validateForm() {
var user = [Link]('user').value;
var pass = [Link]('pass').value;
var email = [Link]('email').value;
if (user == '' || pass == '' || email == '') {
alert('All fields are required!');
return;
}
if ([Link] < 5) {
alert('Username must be at least 5 characters!');
return;
}
if ([Link] < 8) {
alert('Password must be at least 8 characters!');
return;
}
if ([Link]('@') == -1 || [Link]('.') == -1) {
alert('Enter a valid email address!');
return;
}
alert('Form submitted successfully!');
}
</script>
</body>
</html>
Program 4: Sum of Two Numbers (Popup Box)
Accept two numbers via prompt() and display sum in alert().
<!DOCTYPE html>
<html>
<head><title>Sum of Two Numbers</title></head>
<body>
<h2>Sum of Two Numbers</h2>
<button onclick='calcSum()'>Click to Enter Numbers</button>
<script>
function calcSum() {
var a = parseFloat(prompt('Enter first number:'));
var b = parseFloat(prompt('Enter second number:'));
if (isNaN(a) || isNaN(b)) {
alert('Please enter valid numbers!');
return;
}
var sum = a + b;
alert('Sum of ' + a + ' and ' + b + ' = ' + sum);
}
</script>
</body>
</html>
Program 5: Even or Odd Number
Accept a number via prompt and check if it is even or odd.
<!DOCTYPE html>
<html>
<head><title>Even or Odd</title></head>
<body>
<h2>Even or Odd Checker</h2>
<button onclick='checkEvenOdd()'>Check Number</button>
<script>
function checkEvenOdd() {
var num = parseInt(prompt('Enter a number:'));
if (isNaN(num)) {
alert('Please enter a valid number!');
return;
}
if (num % 2 == 0) {
alert(num + ' is an Even number.');
} else {
alert(num + ' is an Odd number.');
}
}
</script>
</body>
</html>
Program 6: Background Color on Button Click (RED / GREEN)
Clicking RED sets background red; clicking GREEN sets it green.
<!DOCTYPE html>
<html>
<head><title>Background Color Changer</title></head>
<body>
<h2>Click a Button to Change Background</h2>
<button onclick='changeColor("red")'>RED</button>
<button onclick='changeColor("green")'>GREEN</button>
<script>
function changeColor(color) {
[Link] = color;
}
</script>
</body>
</html>
Program 7: Auto Background Change Every 2 Seconds (setInterval)
Background color changes automatically every 2 seconds through a list of colors.
<!DOCTYPE html>
<html>
<head><title>Auto Background Color</title></head>
<body>
<h2>Background changes automatically every 2 seconds!</h2>
<script>
var colors = ['red', 'blue', 'green', 'orange', 'purple', 'pink'];
var index = 0;
function changeBg() {
[Link] = colors[index];
index = (index + 1) % [Link]; // cycle back to start
}
// Call changeBg every 2000 milliseconds = 2 seconds
setInterval(changeBg, 2000);
</script>
</body>
</html>
■ Change 2000 to 5000 for 5-second interval.
Program 8: Digital Clock
Displays current hours, minutes, and seconds — updates every 1 second.
<!DOCTYPE html>
<html>
<head>
<title>Digital Clock</title>
<style>
#clock { font-size: 60px; font-family: monospace;
text-align: center; margin-top: 80px; color: #333; }
</style>
</head>
<body>
<div id='clock'>00:00:00</div>
<script>
function showTime() {
var now = new Date();
var h = [Link]();
var m = [Link]();
var s = [Link]();
// Add leading zero if value is less than 10
h = (h < 10) ? '0' + h : h;
m = (m < 10) ? '0' + m : m;
s = (s < 10) ? '0' + s : s;
[Link]('clock').innerHTML = h + ':' + m + ':' + s;
}
showTime(); // show immediately on load
setInterval(showTime, 1000); // update every 1 second
</script>
</body>
</html>
Program 9: Moving Image Left to Right Continuously
An image moves from left to right and resets when it reaches the edge.
<!DOCTYPE html>
<html>
<head>
<title>Moving Image</title>
<style>
body { overflow: hidden; }
#img { position: absolute; top: 100px; left: 0px;
width: 80px; height: 80px; }
</style>
</head>
<body>
<h2 style='text-align:center'>Watch the image move!</h2>
<!-- You can use any image file, or use an emoji as text -->
<img id='img' src='[Link]' alt='Moving Ball' />
<script>
var position = 0;
function moveImage() {
position += 5; // move 5px to the right each frame
// If image goes off screen, reset to left
if (position > [Link]) {
position = 0;
}
[Link]('img').[Link] = position + 'px';
}
// Run moveImage every 30 milliseconds = smooth animation
setInterval(moveImage, 30);
</script>
</body>
</html>
■ If you don't have [Link], replace with any image URL or remove the img tag and animate a div.
Program 10: Set a Cookie
Sets a cookie with a name, value, and expiry of 7 days.
<!DOCTYPE html>
<html>
<head><title>Set Cookie</title></head>
<body>
<h2>Cookie Example</h2>
<button onclick='setCookie()'>Set Cookie</button>
<button onclick='getCookie()'>Get Cookie</button>
<script>
function setCookie() {
var name = 'username';
var value = 'JohnDoe';
var days = 7;
var date = new Date();
[Link]([Link]() + (days * 24 * 60 * 60 * 1000));
var expires = 'expires=' + [Link]();
[Link] = name + '=' + value + '; ' + expires + '; path=/';
alert('Cookie set! Name: ' + name + ', Value: ' + value);
}
function getCookie() {
alert('Cookies: ' + [Link]);
}
</script>
</body>
</html>
Program 11: Radio Buttons Change Background Color
Selecting Red/Blue/Green radio button changes the page background color.
<!DOCTYPE html>
<html>
<head><title>Radio Button Background</title></head>
<body>
<h2>Select a color to change background:</h2>
<input type='radio' name='color' onclick='changeColor("red")' /> Red <br/>
<input type='radio' name='color' onclick='changeColor("blue")' /> Blue <br/>
<input type='radio' name='color' onclick='changeColor("green")'/> Green<br/>
<script>
function changeColor(color) {
[Link] = color;
}
</script>
</body>
</html>
■ SECTION 2 — Form Validation (Programs 12–13)
Program 12: Online Form Validation
All fields required | Valid email (@ and .) | Age between 18 and 60.
<!DOCTYPE html>
<html>
<head><title>Online Form Validation</title></head>
<body>
<h2>Registration Form</h2>
Name: <input type='text' id='name' /><br/><br/>
Email: <input type='text' id='email' /><br/><br/>
Age: <input type='number' id='age' /><br/><br/>
<button onclick='validateForm()'>Submit</button>
<script>
function validateForm() {
var name = [Link]('name').value;
var email = [Link]('email').value;
var age = parseInt([Link]('age').value);
// Check all fields are filled
if (name == '' || email == '' || isNaN(age)) {
alert('All fields are required!');
return;
}
// Validate email
if ([Link]('@') == -1 || [Link]('.') == -1) {
alert('Invalid email! Must contain @ and .');
return;
}
// Validate age
if (age < 18 || age > 60) {
alert('Age must be between 18 and 60!');
return;
}
alert('Form submitted successfully! Welcome, ' + name);
}
</script>
</body>
</html>
Program 13: Alumni Information Form
Name, DOB, Email, Hobbies (checkboxes), Branch (radio) | Age >= 22 from DOB.
<!DOCTYPE html>
<html>
<head><title>Alumni Form</title></head>
<body>
<h2>Alumni Registration Form</h2>
Name: <input type='text' id='name' /><br/><br/>
Date of Birth: <input type='date' id='dob' /><br/><br/>
Email: <input type='text' id='email' /><br/><br/>
Hobbies:<br/>
<input type='checkbox' name='hobby' value='Reading' /> Reading
<input type='checkbox' name='hobby' value='Coding' /> Coding
<input type='checkbox' name='hobby' value='Travelling'/> Travelling<br/><br/>
Branch:<br/>
<input type='radio' name='branch' value='CS' /> CS
<input type='radio' name='branch' value='IT' /> IT
<input type='radio' name='branch' value='EC' /> EC<br/><br/>
<button onclick='validateAlumni()'>Register</button>
<script>
function validateAlumni() {
var name = [Link]('name').value;
var dob = [Link]('dob').value;
var email = [Link]('email').value;
var hobbies = [Link]('input[name=hobby]:checked');
var branch = [Link]('input[name=branch]:checked');
if (!name || !dob || !email) {
alert('Please fill all fields!'); return;
}
if ([Link]('@') == -1 || [Link]('.') == -1) {
alert('Enter a valid email address!'); return;
}
if ([Link] == 0) {
alert('Please select at least one hobby!'); return;
}
if (!branch) {
alert('Please select your branch!'); return;
}
// Age calculation from DOB
var birthDate = new Date(dob);
var today = new Date();
var age = [Link]() - [Link]();
if (age < 22) {
alert('Age must be at least 22 years!'); return;
}
alert('Alumni registered successfully! Age: ' + age);
}
</script>
</body>
</html>
■ SECTION 3 — [Link] (Programs 14–17)
Note: [Link] programs are .js files — run with: node [Link]
Program 14: Simple HTTP Server – Welcome Message
Creates an HTTP server that shows a welcome message in the browser.
// [Link]
// Run: node [Link]
// Open browser: [Link]
const http = require('http'); // built-in [Link] module
// createServer takes a function that handles every request
const server = [Link](function(req, res) {
[Link](200, { 'Content-Type': 'text/html' });
[Link]('<h1>Welcome to My [Link] Server!</h1>');
[Link]('<p>Server is running successfully.</p>');
[Link]();
});
// Start listening on port 3000
[Link](3000, function() {
[Link]('Server is running at [Link]
});
Program 15: Read File & Send as HTTP Response
Reads [Link] using the fs module and sends its content as HTTP response.
// [Link]
// First create a file '[Link]' in the same folder with some text.
// Run: node [Link]
const http = require('http');
const fs = require('fs'); // file system module
const server = [Link](function(req, res) {
// Read the file asynchronously
[Link]('[Link]', 'utf8', function(err, data) {
if (err) {
// If file not found or error, send 500
[Link](500, { 'Content-Type': 'text/plain' });
[Link]('Error: Could not read file!');
return;
}
// Send file content as response
[Link](200, { 'Content-Type': 'text/plain' });
[Link](data);
});
});
[Link](3000, function() {
[Link]('File server running at [Link]
});
Program 16: Express Server – GET, POST, Routing & Error Handling
Install first: npm install express Then run: node [Link]
// [Link]
const express = require('express');
const app = express();
// Middleware to parse JSON request body
[Link]([Link]());
[Link]([Link]({ extended: true }));
// ■■ GET Route: Home Page ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
[Link]('/', function(req, res) {
[Link]('<h1>Welcome to Express Server!</h1>');
});
// ■■ GET Route: with URL parameter ■■■■■■■■■■■■■■■■■■■■
[Link]('/user/:name', function(req, res) {
var name = [Link];
[Link]('<h2>Hello, ' + name + '!</h2>');
});
// ■■ POST Route ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
[Link]('/submit', function(req, res) {
var data = [Link];
[Link]('Data received: ' + [Link](data));
});
// ■■ 404 Error Handler (keep this LAST) ■■■■■■■■■■■■■■■
[Link](function(req, res) {
[Link](404).send('<h2>404 - Page Not Found!</h2>');
});
// Start server
[Link](3000, function() {
[Link]('Express server running on port 3000');
});
Program 17: [Link] Streams – Read & Write Efficiently
Streams handle data in chunks — ideal for large files. Uses pipe() to connect read to write.
// [Link]
// Run: node [Link]
// Make sure '[Link]' exists in same folder.
const fs = require('fs');
// Create a readable stream from [Link]
var readStream = [Link]('[Link]', 'utf8');
// Create a writable stream to [Link]
var writeStream = [Link]('[Link]');
// pipe() connects them: reads from input, writes to output
[Link](writeStream);
// Event: when reading is done
[Link]('end', function() {
[Link]('File has been copied successfully using Streams!');
});
// Event: handle any errors
[Link]('error', function(err) {
[Link]('Error:', [Link]);
});
[Link]('finish', function() {
[Link]('Write stream finished.');
});
■ Use streams for large files (videos, logs). Avoids loading entire file into memory at once.
■ SECTION 4 — React (Programs 18–23)
Setup: npx create-react-app myapp → cd myapp → npm start | Replace contents of src/[Link] with the code below for each program.
Program 18: React – Fetch Data from API & Display as List
Fetches posts from a public API and shows them in a list. Uses useEffect and useState hooks.
// src/[Link]
import React, { useState, useEffect } from 'react';
function App() {
// State to store fetched items
const [items, setItems] = useState([]);
// useEffect runs when component loads (like componentDidMount)
useEffect(function() {
fetch('[Link]
.then(function(response) { return [Link](); })
.then(function(data) { setItems(data); });
}, []); // empty [] means run only ONCE on load
return (
<div>
<h2>Posts from API</h2>
<ul>
{[Link](function(item) {
return <li key={[Link]}>{[Link]}</li>;
})}
</ul>
</div>
);
}
export default App;
Program 19: Express + React Integration – List from Server
Backend (Express) serves data. Frontend (React) fetches and displays it.
// ■■■ BACKEND: [Link] ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
// Run: node [Link] (in one terminal)
// Install: npm install express cors
const express = require('express');
const cors = require('cors');
const app = express();
[Link](cors()); // allow React (port 3000) to access this server
[Link]('/items', function(req, res) {
[Link](['Apple', 'Banana', 'Mango', 'Orange', 'Grapes']);
});
[Link](5000, () => [Link]('Backend running on port 5000'));
// ■■■ FRONTEND: src/[Link] (React) ■■■■■■■■■■■■■■■■■■■■■■
// Run: npm start (in another terminal)
import React, { useState, useEffect } from 'react';
function App() {
const [items, setItems] = useState([]);
useEffect(function() {
fetch('[Link]
.then(res => [Link]())
.then(data => setItems(data));
}, []);
return (
<div>
<h2>Items from Server</h2>
<ul>
{[Link](function(item, index) {
return <li key={index}>{item}</li>;
})}
</ul>
</div>
);
}
export default App;
■ Backend runs on port 5000, React frontend on port 3000. CORS allows cross-port requests.
Program 20: React Class Component 'Car' + [Link]
Create Car class component in [Link] and render it from [Link].
// ■■■ src/[Link] ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
import React, { Component } from 'react';
class Car extends Component {
render() {
return (
<div>
<h2>Car Details</h2>
<p>Name: {[Link]}</p>
<p>Color: {[Link]}</p>
<p>Year: {[Link]}</p>
</div>
);
}
}
export default Car;
// ■■■ src/[Link] ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
import React from 'react';
import ReactDOM from 'react-dom/client';
import Car from './Car';
const root = [Link]([Link]('root'));
[Link](
<Car name='Tesla Model 3' color='Red' year='2023' />
);
Program 21: React Form – Handle Submit & Show Confirmation
Form captures user's name. On submit, shows a confirmation message.
// src/[Link]
import React, { useState } from 'react';
function App() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [submitted, setSubmitted] = useState(false);
function handleSubmit(e) {
[Link](); // stop page from reloading
if (name == '' || email == '') {
alert('Please fill all fields!');
return;
}
setSubmitted(true);
}
// Show confirmation after submit
if (submitted) {
return (
<div>
<h2>Form Submitted Successfully!</h2>
<p>Name: {name}</p>
<p>Email: {email}</p>
</div>
);
}
// Show the form
return (
<div>
<h2>Registration Form</h2>
<form onSubmit={handleSubmit}>
<input
type='text'
placeholder='Enter Name'
value={name}
onChange={e => setName([Link])}
/><br/><br/>
<input
type='email'
placeholder='Enter Email'
value={email}
onChange={e => setEmail([Link])}
/><br/><br/>
<button type='submit'>Submit</button>
</form>
</div>
);
}
export default App;
Program 22: React Hooks – useState Click Counter
Counts how many times the CLICK button is pressed using useState hook.
// src/[Link]
import React, { useState } from 'react';
function App() {
// useState(0) sets initial count to 0
const [count, setCount] = useState(0);
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h2>Button Click Counter</h2>
<p>You clicked the button <b>{count}</b> times.</p>
<button
onClick={() => setCount(count + 1)}
style={{ padding: '10px 20px', fontSize: '18px' }}
>
CLICK
</button>
<br/><br/>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
export default App;
Program 23: React Hooks – Color Selector Buttons
Four buttons: Red, Blue, Green, Yellow. Clicking shows which color was selected.
// src/[Link]
import React, { useState } from 'react';
function App() {
const [selected, setSelected] = useState('');
// List of colors
const colors = ['Red', 'Blue', 'Green', 'Yellow'];
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h2>Select a Color</h2>
{[Link](function(color) {
return (
<button
key={color}
onClick={() => setSelected(color)}
style={{ margin: '8px', padding: '10px 20px',
backgroundColor: [Link](),
color: 'white', fontSize: '16px' }}
>
{color}
</button>
);
})}
{selected !== '' && (
<h3>You have selected: {selected}</h3>
)}
</div>
);
}
export default App;
■ SECTION 5 — XML (Program 24)
Program 24: XML Marksheet – Well-formed & Valid
Save as [Link]. Open in browser or use [Link] to verify.
<?xml version="1.0" encoding="UTF-8"?>
<!--
[Link]
This XML file represents a student semester marksheet.
It is WELL-FORMED because:
1. It has a single root element: <marksheet>
2. All tags are properly opened and closed
3. Tags are correctly nested (no overlap)
4. Attribute values are in quotes
-->
<marksheet>
<student rollno='21CS001'>
<name>John Doe</name>
<semester>5</semester>
<branch>Computer Science</branch>
<subjects>
<subject>
<subjectname>Mathematics</subjectname>
<maxmarks>100</maxmarks>
<marksscored>88</marksscored>
<grade>A</grade>
</subject>
<subject>
<subjectname>Web Technology</subjectname>
<maxmarks>100</maxmarks>
<marksscored>92</marksscored>
<grade>O</grade>
</subject>
<subject>
<subjectname>Data Structures</subjectname>
<maxmarks>100</maxmarks>
<marksscored>75</marksscored>
<grade>B</grade>
</subject>
</subjects>
<totalmarks>255</totalmarks>
<percentage>85</percentage>
<result>PASS</result>
</student>
</marksheet>
■ To prove valid: go to [Link], paste the XML, click Validate. No errors = valid & well-formed.
Well-formed vs Valid — Key Difference:
Term Meaning How to Check
Well-formed Tags properly opened/closed, nested correctly, one root element Open file in any browser – no error = well-formed
Valid Follows rules of a DTD or XML Schema (XSD) file Use [Link] or XML editor
■ Quick Theory Notes (Must Know)
What is a Single Page Application (SPA)?
• A web app that loads only ONE HTML page.
• Content updates dynamically without full page reload.
• Examples: Gmail, Google Maps, Facebook.
• React, Angular, Vue are used to build SPAs.
What is React JSX?
• JSX = JavaScript XML — write HTML inside JavaScript.
• Example: function App() { return Hello! Welcome to React; }
• JSX is not valid JS — Babel tool converts it to regular JavaScript.
• You can use expressions inside JSX using { } curly braces.
What are React Components?
• Components are reusable UI building blocks.
• Class Component: uses class keyword + render() method (older style).
• Function Component: a simple function returning JSX (modern style).
• Props: data passed into components like HTML attributes.
React Hooks — Rules & Examples
• Hooks let function components use state and lifecycle features.
• useState — stores a value: const [count, setCount] = useState(0);
• useEffect — runs code on load: useEffect(() => { fetch(...) }, []);
• RULES: 1) Call Hooks only at TOP LEVEL (not inside if/loops).
• 2) Call Hooks only inside React function components.
• 3) Always import: import { useState } from 'react';
★ All 24 FULL Programs Covered | Best of Luck for Your Exam! ★