This module introduces JavaScript programming for the web. Students will learn variables, functions, DOM manipulation, events, and arrays by building interactive web features.
Duration: 30 minutes
JavaScript variables are hoisted differently based on declaration keyword. let and const are block-scoped (ES6), while var is function-scoped. Always prefer const by default, use let when reassignment is needed. Students should verify AI-generated variable declarations for scope bugs.
Open VS Code and create a new file variables.html. Walk through each data type in the console. Show how let can be reassigned but const cannot. Demonstrate the difference between == and ===.
// TODO: Declare variables using let and const
// TODO: Store name (string), age (number), isStudent (boolean)
// TODO: Log each variable and its type to the console
// TODO: Try changing a const value and observe the error
let name = "John";
let age = 25;
let isStudent = true;
console.log(name);
console.log(typeof age);
// Variable declarations
const studentName = "Sarah";
let age = 22;
let isEnrolled = true;
let gpa = 3.8;
const school = "Code Academy";
// Type checking
console.log("Name:", studentName, "| Type:", typeof studentName);
console.log("Age:", age, "| Type:", typeof age);
console.log("Enrolled:", isEnrolled, "| Type:", typeof isEnrolled);
console.log("GPA:", gpa, "| Type:", typeof gpa);
// Reassignment demonstration
age = 23;
console.log("Updated age:", age);
// const cannot be reassigned
// school = "New School"; // This will throw an error
// Type coercion examples
let score = "85";
let newScore = score + 5;
console.log("String concatenation:", newScore); // "855"
let correctScore = Number(score) + 5;
console.log("Number conversion:", correctScore); // 90
const for your hometown and a let for your age. Attempt to reassign both and note which throws an error.Answer: B
typeof null return in JavaScript?
Answer: C
Answer: B
const variable?
Answer: B
typeof "hello"?
Answer: B
Duration: 45 minutes
Functions are the building blocks of JavaScript programs. Arrow functions (=>) have lexical this binding, which students will encounter later. Focus on basic syntax first. Remind students to always verify AI-generated function logic with manual testing.
Create functions.html and demonstrate calling a function before and after its declaration. Show how variables declared inside a function are not accessible outside.
// TODO: Create a function called greet that takes a name parameter
// TODO: Create a function called add that takes two numbers
// TODO: Test what happens when you call a function before declaring it
// TODO: Try accessing a variable declared inside a function from outside
function greet(name) {
let message = "Hello, " + name;
console.log(message);
}
function add(a, b) {
return a + b;
}
console.log(add(5, 3));
// Function Declaration
function calculateArea(width, height) {
const area = width * height;
return area;
}
// Function Expression
const calculatePerimeter = function(width, height) {
return 2 * (width + height);
};
// Arrow Function
const calculateVolume = (width, height, depth) => width * height * depth;
// Testing functions
console.log("Area:", calculateArea(5, 10));
console.log("Perimeter:", calculatePerimeter(5, 10));
console.log("Volume:", calculateVolume(5, 10, 3));
// Scope demonstration
let globalVar = "I'm global";
function scopeDemo() {
let functionVar = "I'm function-scoped";
if (true) {
let blockVar = "I'm block-scoped";
console.log("Inside block:", globalVar, functionVar, blockVar);
}
// console.log(blockVar); // ReferenceError
console.log("Inside function:", globalVar, functionVar);
}
scopeDemo();
console.log("Outside function:", globalVar);
// console.log(functionVar); // ReferenceError
// console.log(blockVar); // ReferenceError
Answer: C
typeof calculateArea for a function declaration?
Answer: B
Answer: B
Answer: B
this binding ✅Answer: B
Duration: 45 minutes
The DOM (Document Object Model) is a programming interface for HTML documents. It represents the page as a tree of objects. Students should practice selecting elements by ID, class, and tag. Always verify AI-generated DOM manipulation code by inspecting the actual element in DevTools.
Create dom.html with a heading and a button. Use JavaScript to change the heading text and style when the button is clicked. Also demonstrate adding a new paragraph element to the page.
<!DOCTYPE html>
<html>
<head>
<title>DOM Practice</title>
</head>
<body>
<h1 id="title">Original Title</h1>
<p id="desc">Original Description</p>
<button id="btn">Change Content</button>
<script>
// TODO: Select the h1 element by ID
// TODO: Change its text content to "Updated Title"
// TODO: Change the paragraph text
// TODO: Change the button text
// TODO: Add a new div with class "new-box" to the body
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation Demo</title>
<style>
.new-box {
background-color: #e0f7fa;
padding: 15px;
margin: 10px 0;
border-radius: 5px;
font-family: Arial, sans-serif;
}
.highlight {
color: #d32f2f;
font-weight: bold;
}
</style>
</head>
<body>
<h1 id="mainTitle">Welcome to JavaScript</h1>
<p id="description">Learn DOM manipulation step by step.</p>
<button id="actionBtn">Click Me</button>
<ul id="itemList"></ul>
<script>
// Select elements
const title = document.getElementById('mainTitle');
const desc = document.getElementById('description');
const btn = document.getElementById('actionBtn');
const list = document.getElementById('itemList');
// Modify content
title.textContent = 'Updated: DOM Mastery';
desc.innerHTML = 'You are learning <span class="highlight">DOM</span> manipulation!';
// Modify styles
title.style.color = '#1976d2';
title.style.fontSize = '2rem';
// Modify button
btn.textContent = 'Clicked!';
btn.style.backgroundColor = '#4caf50';
btn.style.color = 'white';
// Create new element
const newDiv = document.createElement('div');
newDiv.className = 'new-box';
newDiv.textContent = 'I was created dynamically with JavaScript!';
document.body.appendChild(newDiv);
// Add list item
const listItem = document.createElement('li');
listItem.textContent = 'First dynamic list item';
list.appendChild(listItem);
</script>
</body>
</html>
<li> element with the text "New Item" and append it to an existing <ul>.<h2> elements to 24px using querySelectorAll.innerHTML and textContent. When should you use each?Answer: C
Answer: B
Answer: A
document.getElementById('app') return if no element has that ID?
Answer: A
Answer: D
Duration: 40 minutes
Events enable interactivity. The addEventListener method is preferred over inline event handlers (onclick). Students should verify AI-generated event code by testing all event types they plan to use. Common mistake: forgetting to call preventDefault() on form submit buttons.
Create events.html with a button, an input field, and a form. Attach click, keydown, and submit events. Show how to prevent form submission and log the event target.
<!DOCTYPE html>
<html>
<head>
<title>Events Practice</title>
</head>
<body>
<button id="myBtn">Click Me</button>
<input type="text" id="myInput" placeholder="Type something...">
<form id="myForm">
<input type="text" placeholder="Enter name">
<button type="submit">Submit</button>
</form>
<script>
// TODO: Add click event to button that logs "Button clicked!"
// TODO: Add keydown event to input that logs the key pressed
// TODO: Add submit event to form that prevents default and logs data
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Events</title>
<style>
body { font-family: Arial, sans-serif; max-width: 600px; margin: 2rem auto; padding: 0 1rem; }
button { padding: 10px 20px; margin: 5px; cursor: pointer; }
.box { width: 150px; height: 150px; background-color: #1976d2; margin: 20px 0; transition: all 0.3s; }
.box:hover { background-color: #d32f2f; transform: scale(1.1); }
input { padding: 8px; margin: 5px; width: 200px; }
</style>
</head>
<body>
<h1>JavaScript Events Demo</h1>
<button id="clickBtn">Click Me</button>
<button id="dblClickBtn">Double Click Me</button>
<input type="text" id="keyInput" placeholder="Type to see key events">
<p id="keyDisplay">Last key: None</p>
<div id="hoverBox" class="box"></div>
<p id="hoverText">Hover over the box</p>
<form id="demoForm">
<input type="email" id="emailInput" placeholder="Enter your email" required>
<button type="submit">Subscribe</button>
</form>
<p id="formMessage"></p>
<script>
// Click event
document.getElementById('clickBtn').addEventListener('click', function(event) {
console.log('Button clicked!', event.target);
alert('You clicked the button!');
});
// Double click event
document.getElementById('dblClickBtn').addEventListener('dblclick', function() {
this.style.backgroundColor = '#4caf50';
this.textContent = 'Double Clicked!';
});
// Keydown event
const keyInput = document.getElementById('keyInput');
const keyDisplay = document.getElementById('keyDisplay');
keyInput.addEventListener('keydown', function(event) {
keyDisplay.textContent = 'Last key: ' + event.key;
});
// Mouseover event
const hoverBox = document.getElementById('hoverBox');
const hoverText = document.getElementById('hoverText');
hoverBox.addEventListener('mouseover', function() {
hoverText.textContent = 'You are hovering!';
});
hoverBox.addEventListener('mouseout', function() {
hoverText.textContent = 'Hover over the box';
});
// Submit event with preventDefault
document.getElementById('demoForm').addEventListener('submit', function(event) {
event.preventDefault();
const email = document.getElementById('emailInput').value;
const message = document.getElementById('formMessage');
if (email) {
message.textContent = 'Subscribed with: ' + email;
message.style.color = 'green';
} else {
message.textContent = 'Please enter an email.';
message.style.color = 'red';
}
});
</script>
</body>
</html>
event.target and event.currentTarget. Write a summary with examples.Answer: B
event.preventDefault() do?
Answer: B
Answer: C
Answer: B
Answer: D
Duration: 45 minutes
Arrays store ordered lists; objects store key-value pairs. Students should verify AI-generated array method chains by testing them step by step. Common mistakes include mutating the original array when an immutable method was intended.
Create arrays.html with a list of student names. Use array methods to add, remove, and transform data. Display results in the DOM.
// TODO: Create an array of 3 student names
// TODO: Add a new name to the end of the array
// TODO: Remove the first name from the array
// TODO: Create an array of numbers and filter only even numbers
// TODO: Create an object for a student with name, age, and grade
let students = ["Alice", "Bob", "Charlie"];
let numbers = [1, 2, 3, 4, 5, 6];
function filterEvens(arr) {
// TODO: Implement filter for even numbers
}
// Array operations
const students = ['Alice', 'Bob', 'Charlie'];
console.log('Original:', students);
// Add to end
students.push('Diana');
console.log('After push:', students);
// Remove from end
students.pop();
console.log('After pop:', students);
// Add to beginning
students.unshift('Eve');
console.log('After unshift:', students);
// Remove from beginning
students.shift();
console.log('After shift:', students);
// Map - transform each element
const ages = [20, 22, 19, 24];
const agesNextYear = ages.map(age => age + 1);
console.log('Ages next year:', agesNextYear);
// Filter - keep elements matching condition
const evenAges = ages.filter(age => age % 2 === 0);
console.log('Even ages:', evenAges);
// Find - get first matching element
const age23 = ages.find(age => age > 22);
console.log('First age > 22:', age23);
// ForEach - loop through array
students.forEach((student, index) => {
console.log(`Student ${index + 1}: ${student}`);
});
// Object operations
const student = {
name: 'Alice',
age: 20,
grade: 'A',
courses: ['Math', 'Science', 'English'],
address: {
city: 'New York',
country: 'USA'
}
};
// Access properties
console.log('Name:', student.name);
console.log('First course:', student.courses[0]);
console.log('City:', student.address.city);
// Modify properties
student.age = 21;
student.email = 'alice@example.com';
// Object methods
const keys = Object.keys(student);
const values = Object.values(student);
console.log('Keys:', keys);
console.log('Values:', values);
// Array of objects
const classRoster = [
{ name: 'Alice', grade: 'A' },
{ name: 'Bob', grade: 'B' },
{ name: 'Charlie', grade: 'A' }
];
const aStudents = classRoster.filter(s => s.grade === 'A');
console.log('A students:', aStudents);
map to double each number and filter to keep only numbers greater than 10.filter and indexOf.map and forEach. Write a summary.Answer: B
array.push() return?
Answer: B
user?
Answer: C
Answer: A
array.filter() return?
Answer: A