JavaScript Experiments (1–30)
1. Hello World in JavaScript
Standalone: Run this file with a browser (via an HTML file) or [Link].
// File: [Link]
[Link]("Hello World");
2. Variables & Data Types
// File: [Link]
let name = "Alice";
const age = 30;
var isStudent = false;
[Link]("Name:", name);
[Link]("Age:", age);
[Link]("Is Student:", isStudent);
[Link]("Type of name:", typeof name);
[Link]("Type of age:", typeof age);
[Link]("Type of isStudent:", typeof isStudent);
3. Operators and Expressions
// File: [Link]
let a = 10, b = 5;
[Link]("Addition:", a + b);
[Link]("Subtraction:", a - b);
[Link]("Multiplication:", a * b);
[Link]("Division:", a / b);
[Link]("Is a greater than b?", a > b);
4. Conditional Statements
// File: [Link]
let score = 85;
if (score >= 90) {
[Link]("Grade A");
} else if (score >= 80) {
[Link]("Grade B");
} else {
[Link]("Grade C");
}
switch(score) {
case 85:
[Link]("Exactly 85!");
break;
default:
[Link]("Score not 85");
}
5. Loops and Iteration
// File: [Link]
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < [Link]; i++) {
[Link]("For loop:", numbers[i]);
}
let i = 0;
while (i < [Link]) {
[Link]("While loop:", numbers[i]);
i++;
}
6. Function Declarations & Expressions
// File: [Link]
// Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
[Link](greet("Alice"));
// Function Expression
const square = function(num) {
return num * num;
};
[Link]("Square of 5:", square(5));
7. Arrow Functions (ES6)
// File: [Link]
const add = (x, y) => x + y;
[Link]("Sum:", add(10, 15));
8. Working with Arrays
// File: [Link]
let fruits = ["apple", "banana", "orange"];
[Link]("mango");
[Link]("Fruits:", fruits);
[Link]("First fruit:", fruits[0]);
9. Array Methods: Map, Filter, and Reduce
// File: [Link]
let numbers = [1, 2, 3, 4, 5];
const doubled = [Link](num => num * 2);
[Link]("Doubled:", doubled);
const evens = [Link](num => num % 2 === 0);
[Link]("Evens:", evens);
const sum = [Link]((acc, num) => acc + num, 0);
[Link]("Sum:", sum);
10. Objects and Object Literals
// File: [Link]
const person = {
name: "Alice",
age: 30,
greet: function() { return "Hi, I'm " + [Link]; }
};
[Link]([Link]());
11. DOM Manipulation
Save the following as an HTML file and open it in your browser.
<!-- File: [Link] -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM Manipulation</title>
</head>
<body>
<div id="content">Old Content</div>
<script>
const contentDiv = [Link]("content");
[Link] = "New Content set by JavaScript!";
</script>
</body>
</html>
12. Event Handling
Save this as an HTML file.
<!-- File: [Link] -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event Handling</title>
</head>
<body>
<button id="myButton">Click Me</button>
<script>
[Link]("myButton").addEventListener("click",
function() {
alert("Button was clicked!");
});
</script>
</body>
</html>
13. Form Handling & Validation
Save this as an HTML file.
<!-- File: [Link] -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Validation</title>
</head>
<body>
<form id="myForm">
<input type="text" id="username" placeholder="Enter username"
required>
<button type="submit">Submit</button>
</form>
<script>
[Link]("myForm").addEventListener("submit",
function(e) {
[Link]();
const username = [Link]("username").value;
if ([Link]() === "") {
alert("Username cannot be empty!");
} else {
alert("Form submitted with username: " + username);
}
});
</script>
</body>
</html>
14. JSON Parsing and Stringifying
// File: [Link]
const obj = { name: "Alice", age: 30 };
const jsonStr = [Link](obj);
[Link]("JSON String:", jsonStr);
const parsedObj = [Link](jsonStr);
[Link]("Parsed Object:", parsedObj);
15. Callbacks in JavaScript
// File: [Link]
function doTask(callback) {
[Link]("Task started...");
setTimeout(() => {
[Link]("Task completed!");
callback();
}, 1000);
}
doTask(() => {
[Link]("Callback executed after task.");
});
16. Promises and Chaining
// File: [Link]
const promiseExample = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise resolved!");
}, 1000);
});
promiseExample
.then(result => {
[Link](result);
return "Next value";
})
.then(next => {
[Link](next);
})
.catch(error => {
[Link]("Error:", error);
});
17. Async/Await
// File: [Link]
async function fetchData() {
try {
const response = await
fetch("[Link]
const data = await [Link]();
[Link]("Data:", data);
} catch (error) {
[Link]("Error fetching data:", error);
}
}
fetchData();
18. Error Handling with Try/Catch
// File: [Link]
try {
// This will throw an error because the function is not defined
let result = nonExistentFunction();
} catch (error) {
[Link]("Caught an error:", [Link]);
} finally {
[Link]("Cleanup if necessary.");
}
19. Closures in JavaScript
// File: [Link]
function outer() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = outer();
[Link]("Counter:", counter()); // 1
[Link]("Counter:", counter()); // 2
20. Immediately Invoked Function Expressions (IIFE)
// File: [Link]
(function() {
[Link]("IIFE executed immediately!");
})();
21. Module System (ES6 Modules)
Note: Save these as two separate files and run with a module-supporting environment (or
bundler).
o File: [Link]
// File: [Link]
export function add(a, b) {
return a + b;
}
o File: [Link]
// File: [Link]
import { add } from './[Link]';
[Link]("Addition:", add(5, 7));
22. Working with LocalStorage
Save as an HTML file with embedded script.
<!-- File: [Link] -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LocalStorage Example</title>
</head>
<body>
<script>
[Link]("username", "Alice");
[Link]("Stored username:", [Link]("username"));
[Link]("username");
</script>
</body>
</html>
23. SessionStorage Example
Save as an HTML file.
<!-- File: [Link] -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SessionStorage Example</title>
</head>
<body>
<script>
[Link]("sessionID", "ABC123");
[Link]("Session ID:", [Link]("sessionID"));
[Link]("sessionID");
</script>
</body>
</html>
24. Fetch API for HTTP Requests
// File: [Link]
fetch("[Link]
.then(response => [Link]())
.then(data => [Link]("Post data:", data))
.catch(error => [Link]("Error:", error));
25. AJAX with XMLHttpRequest
// File: [Link]
const xhr = new XMLHttpRequest();
[Link]("GET", "[Link] true);
[Link] = function() {
if ([Link] === 200) {
[Link]("AJAX response:", [Link]);
}
};
[Link]();
26. Prototype and Inheritance
// File: [Link]
function Animal(name) {
[Link] = name;
}
[Link] = function() {
[Link]([Link] + " makes a noise.");
};
function Dog(name) {
[Link](this, name);
}
[Link] = [Link]([Link]);
[Link] = function() {
[Link]([Link] + " barks.");
};
const dog = new Dog("Buddy");
[Link]();
27. Class-based Syntax (ES6)
// File: [Link]
class Person {
constructor(name, age) {
[Link] = name;
[Link] = age;
}
greet() {
return `Hi, I'm ${[Link]}`;
}
}
const person1 = new Person("Alice", 30);
[Link]([Link]());
28. Recursion in JavaScript
// File: [Link]
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
[Link]("Factorial of 5:", factorial(5));
29. Debouncing and Throttling Techniques
// File: [Link]
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => [Link](this, args), delay);
};
}
[Link]('resize', debounce(() => {
[Link]("Window resized!");
}, 500));
30. Regular Expressions
// File: [Link]
function validateEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return [Link](email);
}
[Link]("Valid email:", validateEmail("test@[Link]"));
[Link]("Invalid email:", validateEmail("test@.com"));
[Link] Experiments (31–50)
31. Basic [Link] Script
// File: [Link]
[Link]("Hello from [Link]");
Run with: node [Link]
32. File System Module – Reading Files
Ensure there is a file named [Link] in the same directory.
// File: [Link]
const fs = require('fs');
[Link]('[Link]', 'utf8', (err, data) => {
if (err) return [Link](err);
[Link]("File content:", data);
});
33. File System Module – Writing Files
// File: [Link]
const fs = require('fs');
const content = "Hello, this is a test file.";
[Link]('[Link]', content, err => {
if (err) return [Link](err);
[Link]("File written successfully.");
});
34. EventEmitter Basics
// File: [Link]
const EventEmitter = require('events');
const emitter = new EventEmitter();
[Link]('greet', () => {
[Link]("Hello Event!");
});
[Link]('greet');
35. Building a Simple HTTP Server
// File: [Link]
const http = require('http');
const server = [Link]((req, res) => {
[Link](200, {'Content-Type': 'text/plain'});
[Link]("Hello World from [Link] HTTP server!");
});
[Link](3000, () => {
[Link]("Server listening on port 3000");
});
36. Routing with HTTP Module
// File: [Link]
const http = require('http');
const server = [Link]((req, res) => {
if ([Link] === '/') {
[Link](200, {'Content-Type': 'text/plain'});
[Link]("Welcome to the homepage!");
} else if ([Link] === '/about') {
[Link](200, {'Content-Type': 'text/plain'});
[Link]("About us page");
} else {
[Link](404, {'Content-Type': 'text/plain'});
[Link]("404 Not Found");
}
});
[Link](3000, () => {
[Link]("Server running on port 3000");
});
37. Introduction to [Link]
Ensure Express is installed (npm install express).
// File: [Link]
const express = require('express');
const app = express();
[Link]('/', (req, res) => {
[Link]("Hello from Express!");
});
[Link](3000, () => {
[Link]("Express server listening on port 3000");
});
38. Express Middleware
// File: [Link]
const express = require('express');
const app = express();
// Custom middleware to log each request
[Link]((req, res, next) => {
[Link](`${[Link]} ${[Link]}`);
next();
});
[Link]('/', (req, res) => {
[Link]("Middleware example with Express.");
});
[Link](3000, () => {
[Link]("Server running on port 3000");
});
39. REST API – GET Endpoint
// File: [Link]
const express = require('express');
const app = express();
[Link]('/api/data', (req, res) => {
[Link]({ message: "Data fetched successfully", data: [1, 2, 3, 4,
5] });
});
[Link](3000, () => {
[Link]("API server running on port 3000");
});
40. REST API – POST Endpoint
// File: [Link]
const express = require('express');
const app = express();
[Link]([Link]());
[Link]('/api/data', (req, res) => {
const receivedData = [Link];
[Link]({ message: "Data received successfully", data: receivedData
});
});
[Link](3000, () => {
[Link]("API server running on port 3000");
});
41. CRUD Operations with Express
// File: [Link]
const express = require('express');
const app = express();
[Link]([Link]());
let items = []; // In-memory data store
// Create
[Link]('/api/items', (req, res) => {
const item = { id: [Link] + 1, name: [Link] };
[Link](item);
[Link](item);
});
// Read
[Link]('/api/items', (req, res) => {
[Link](items);
});
// Update
[Link]('/api/items/:id', (req, res) => {
const id = parseInt([Link]);
let item = [Link](i => [Link] === id);
if (item) {
[Link] = [Link];
[Link](item);
} else {
[Link](404).json({ message: "Item not found" });
}
});
// Delete
[Link]('/api/items/:id', (req, res) => {
const id = parseInt([Link]);
items = [Link](i => [Link] !== id);
[Link]({ message: "Item deleted" });
});
[Link](3000, () => {
[Link]("CRUD API server running on port 3000");
});
42. Template Engines with Express (Using EJS)
Make sure to install EJS (npm install ejs). Create the file views/[Link] as
shown below.
o File: [Link]
// File: [Link]
const express = require('express');
const app = express();
[Link]('view engine', 'ejs');
[Link]('/', (req, res) => {
[Link]('index', { title: "EJS Example", message: "Hello
from EJS" });
});
[Link](3000, () => {
[Link]("EJS server running on port 3000");
});
o File: views/[Link]
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= message %></h1>
</body>
</html>
43. Implementing JWT Authentication
Install jsonwebtoken via npm install jsonwebtoken.
// File: [Link]
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
[Link]([Link]());
const secretKey = "mySecretKey";
// Login route to generate token
[Link]('/login', (req, res) => {
// Dummy user for demonstration; use real authentication in practice.
const user = { id: 1, username: [Link] };
const token = [Link](user, secretKey, { expiresIn: '1h' });
[Link]({ token });
});
// Protected route
[Link]('/protected', (req, res) => {
const token = [Link]['authorization'];
if (!token) return [Link](401).send("Access Denied");
try {
const verified = [Link](token, secretKey);
[Link]({ message: "Protected data", user: verified });
} catch (err) {
[Link](400).send("Invalid Token");
}
});
[Link](3000, () => {
[Link]("JWT auth server running on port 3000");
});
44. [Link] Integration
Install passport and passport-local via npm install passport passport-local.
// File: [Link]
const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const app = express();
[Link]([Link]());
[Link]([Link]());
[Link](new LocalStrategy(
function(username, password, done) {
// Replace this with real user validation
if (username === "admin" && password === "password") {
return done(null, { id: 1, username: "admin" });
} else {
return done(null, false, { message: "Incorrect credentials" });
}
}
));
[Link]('/login', [Link]('local', { session: false }),
(req, res) => {
[Link]({ message: "Logged in successfully", user: [Link] });
});
[Link](3000, () => {
[Link]("[Link] server running on port 3000");
});
45. Handling File Uploads with Multer
Install multer via npm install multer. Ensure an uploads/ folder exists or let Multer
create it.
// File: [Link]
const express = require('express');
const multer = require('multer');
const app = express();
const storage = [Link]({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, [Link]() + '-' + [Link]);
}
});
const upload = multer({ storage: storage });
[Link]('/upload', [Link]('myFile'), (req, res) => {
[Link]({ message: "File uploaded successfully", file: [Link] });
});
[Link](3000, () => {
[Link]("File upload server running on port 3000");
});
46. Real-Time Chat with [Link]
Install [Link] via npm install [Link] express. Save server and client files
separately.
o Server: File: [Link]
// File: [Link]
const express = require('express');
const http = require('http');
const socketIo = require('[Link]');
const app = express();
const server = [Link](app);
const io = socketIo(server);
[Link]('connection', (socket) => {
[Link]("New client connected");
[Link]('chat message', (msg) => {
[Link]('chat message', msg);
});
[Link]('disconnect', () => {
[Link]("Client disconnected");
});
});
[Link](3000, () => {
[Link]("[Link] server running on port 3000");
});
o Client: File: [Link]
<!DOCTYPE html>
<html>
<head>
<title>[Link] Chat</title>
<script src="/[Link]/[Link]"></script>
</head>
<body>
<ul id="messages"></ul>
<form id="chatForm">
<input id="msgInput" autocomplete="off"
/><button>Send</button>
</form>
<script>
const socket = io();
const form = [Link]('chatForm');
const input = [Link]('msgInput');
const messages = [Link]('messages');
[Link]('submit', (e) => {
[Link]();
[Link]('chat message', [Link]);
[Link] = '';
});
[Link]('chat message', (msg) => {
const li = [Link]('li');
[Link] = msg;
[Link](li);
});
</script>
</body>
</html>
47. REST API Testing with Postman
This is a Postman collection snippet (save as a JSON file and import into Postman).
{
"info": {
"name": "Test API",
"_postman_id": "12345",
"schema":
"[Link]
},
"item": [
{
"name": "GET Data",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "[Link]
"protocol": "http",
"host": ["localhost"],
"port": "3000",
"path": ["api", "data"]
}
}
}
]
}
48. Building a Simple Microservice
// File: [Link]
const express = require('express');
const app = express();
[Link]([Link]());
[Link]('/microservice', (req, res) => {
[Link]({ message: "Response from microservice" });
});
[Link](3000, () => {
[Link]("Microservice running on port 3000");
});
49. Using Environment Variables with dotenv
Install dotenv with npm install dotenv and create a .env file with PORT=3000.
// File: [Link]
require('dotenv').config();
const express = require('express');
const app = express();
const port = [Link] || 3000;
[Link]('/', (req, res) => {
[Link]("Environment variable example using dotenv");
});
[Link](port, () => {
[Link](`Server running on port ${port}`);
});
50. Deployment of a [Link] Application
A simple Express app ready for deployment (e.g., on Heroku or AWS).
// File: [Link]
const express = require('express');
const app = express();
const port = [Link] || 3000;
[Link]('/', (req, res) => {
[Link]("Deployed [Link] application running!");
});
[Link](port, () => {
[Link](`Server running on port ${port}`);
});