العربية

Module 6: JavaScript

Prerequisites: Modules 1-5 (HTML, CSS, Bootstrap, Prompt Engineering, AI Tools)

Estimated Duration: 3-4 hours

Tools: VS Code, Live Server, Browser DevTools

Module Overview

This module introduces JavaScript programming for the web. Students will learn variables, functions, DOM manipulation, events, and arrays by building interactive web features.


Lesson 1: Variables and Data Types

Duration: 30 minutes

Learning Objectives

Instructor Notes

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.

Presentation Outline

  1. What is JavaScript? (5 min)
  2. Variables: var, let, const (10 min)
  3. Data types overview (5 min)
  4. Type coercion and typeof operator (5 min)
  5. Best practices (5 min)

Demonstration

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 ===.

AI Prompts

  1. "Generate JavaScript examples showing var, let, and const differences with scope explanations"
  2. "Create a JavaScript type coercion quiz with common pitfalls"
  3. "Write a JavaScript variables cheat sheet for beginners"

Starter Code

// 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);

Final Code

// 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

Exercises

  1. Create variables for your favorite movie, release year, and rating. Log each with its type.
  2. Declare a const for your hometown and a let for your age. Attempt to reassign both and note which throws an error.
  3. Write code that converts a string number "42" to a number, adds 10, and logs the result.

Homework

  1. Research the 7 primitive data types in JavaScript. Write a paragraph explaining each.
  2. Create a JavaScript file that declares variables for a person (name, age, email, isVerified). Print them in a formatted sentence.

Quiz

  1. Which keyword creates a block-scoped variable that can be reassigned?
    • A) var
    • B) let ✅
    • C) const
    • D) static

    Answer: B

  2. What does typeof null return in JavaScript?
    • A) "null"
    • B) "undefined"
    • C) "object" ✅
    • D) "boolean"

    Answer: C

  3. Which data type is NOT a primitive in JavaScript?
    • A) Symbol
    • B) Array ✅
    • C) BigInt
    • D) Boolean

    Answer: B

  4. What happens when you try to reassign a const variable?
    • A) It silently changes value
    • B) It throws a TypeError ✅
    • C) It returns undefined
    • D) It converts to var

    Answer: B

  5. What is the output of typeof "hello"?
    • A) "text"
    • B) "string" ✅
    • C) "String"
    • D) "char"

    Answer: B


Lesson 2: Functions and Scope

Duration: 45 minutes

Learning Objectives

Instructor Notes

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.

Presentation Outline

  1. Why functions matter (5 min)
  2. Function declaration vs expression (10 min)
  3. Parameters and return values (10 min)
  4. Scope: global, function, block (10 min)

Demonstration

Create functions.html and demonstrate calling a function before and after its declaration. Show how variables declared inside a function are not accessible outside.

AI Prompts

  1. "Generate JavaScript function examples: declaration, expression, arrow function with same logic"
  2. "Create a scope diagram showing global vs function vs block scope in JavaScript"
  3. "Write debugging exercises for common JavaScript scope errors"

Starter Code

// 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));

Final Code

// 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

Exercises

  1. Write a function that converts Celsius to Fahrenheit. Test it with 0, 100, and 37.8.
  2. Create a function with default parameters that greets a user with "Hello, [name]!" or "Hello, Guest!" if no name is provided.
  3. Write a function that checks if a number is even or odd and returns a boolean.

Homework

  1. Create a JavaScript calculator with functions for add, subtract, multiply, and divide. Each function should return the result.
  2. Research the difference between function declarations and function expressions. Write a summary with examples.

Quiz

  1. Which function syntax supports default parameters?
    • A) Only function declarations
    • B) Only arrow functions
    • C) All modern function syntaxes ✅
    • D) Only function expressions

    Answer: C

  2. What is the output of typeof calculateArea for a function declaration?
    • A) "undefined"
    • B) "function" ✅
    • C) "object"
    • D) "number"

    Answer: B

  3. Which keyword creates a block-scoped variable?
    • A) var
    • B) let ✅
    • C) Both var and let
    • D) Neither

    Answer: B

  4. What does a function return if no return statement is executed?
    • A) null
    • B) undefined ✅
    • C) 0
    • D) false

    Answer: B

  5. Arrow functions differ from regular functions in that they:
    • A) Cannot have parameters
    • B) Do not have their own this binding ✅
    • C) Always return undefined
    • D) Cannot be assigned to variables

    Answer: B


Lesson 3: DOM Manipulation

Duration: 45 minutes

Learning Objectives

Instructor Notes

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.

Presentation Outline

  1. What is the DOM? (5 min)
  2. Selecting elements (10 min)
  3. Modifying content and styles (10 min)
  4. Creating elements dynamically (10 min)

Demonstration

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.

AI Prompts

  1. "Generate JavaScript DOM manipulation examples: select, modify, create elements with explanations"
  2. "Create a DOM manipulation cheat sheet for beginners with common methods"
  3. "Write a JavaScript exercise where students build a dynamic to-do list item creator"

Starter Code

<!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>

Final Code

<!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>

Exercises

  1. Select a paragraph by class name and change its background color to yellow.
  2. Create a new <li> element with the text "New Item" and append it to an existing <ul>.
  3. Change the font size of all <h2> elements to 24px using querySelectorAll.

Homework

  1. Build a simple web page with a heading, a paragraph, and a button. When clicked, the button changes the heading color and text.
  2. Research the difference between innerHTML and textContent. When should you use each?

Quiz

  1. Which method selects the first element matching a CSS selector?
    • A) getElementById
    • B) getElementsByClassName
    • C) querySelector ✅
    • D) querySelectorAll

    Answer: C

  2. What is the correct way to change only the text content of an element?
    • A) element.innerHTML = "text"
    • B) element.textContent = "text" ✅
    • C) element.value = "text"
    • D) element.innerText = "text" (also correct, but B is most common)

    Answer: B

  3. Which method creates a new HTML element?
    • A) document.createElement() ✅
    • B) document.newElement()
    • C) document.append()
    • D) document.createNode()

    Answer: A

  4. What does document.getElementById('app') return if no element has that ID?
    • A) null ✅
    • B) undefined
    • C) An empty string
    • D) It throws an error

    Answer: A

  5. How do you append a child element to a parent?
    • A) parent.append(child)
    • B) parent.appendChild(child)
    • C) parent.add(child)
    • D) Both A and B ✅

    Answer: D


Lesson 4: Events

Duration: 40 minutes

Learning Objectives

Instructor Notes

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.

Presentation Outline

  1. What are events? (5 min)
  2. addEventListener syntax (10 min)
  3. Common event types (10 min)
  4. Event object and preventDefault (10 min)

Demonstration

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.

AI Prompts

  1. "Generate JavaScript event listener examples for click, mouseover, keydown, and submit events"
  2. "Create an interactive web component using vanilla JavaScript events"
  3. "Write exercises for common event handling mistakes and their fixes"

Starter Code

<!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>

Final Code

<!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>

Exercises

  1. Add a keyup event to an input that displays the current value in a paragraph in real time.
  2. Create a button that changes the background color of the page to a random color when clicked.
  3. Build a form with validation that shows an error message if the input is empty when submitted.

Homework

  1. Build a simple counter with +, -, and Reset buttons. Display the count in a heading.
  2. Research the difference between event.target and event.currentTarget. Write a summary with examples.

Quiz

  1. Which method is the recommended way to attach event handlers?
    • A) element.onclick = function
    • B) element.addEventListener('click', function) ✅
    • C) element.addEvent('click', function)
    • D) element.on('click', function)

    Answer: B

  2. What does event.preventDefault() do?
    • A) Stops the event from bubbling
    • B) Stops the default browser action ✅
    • C) Removes the event listener
    • D) Prevents the event from firing

    Answer: B

  3. Which event fires when a user releases a key?
    • A) keydown
    • B) keypress
    • C) keyup ✅
    • D) keyrelease

    Answer: C

  4. What property gives you the element that triggered the event?
    • A) event.currentTarget
    • B) event.target ✅
    • C) event.srcElement
    • D) event.trigger

    Answer: B

  5. Which event combination detects a double-click?
    • A) Two click events
    • B) dblclick event
    • C) click event with a timer
    • D) Both B and C work ✅

    Answer: D


Lesson 5: Arrays and Objects

Duration: 45 minutes

Learning Objectives

Instructor Notes

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.

Presentation Outline

  1. Arrays basics (10 min)
  2. Array methods (10 min)
  3. Objects basics (10 min)
  4. Iteration techniques (10 min)

Demonstration

Create arrays.html with a list of student names. Use array methods to add, remove, and transform data. Display results in the DOM.

AI Prompts

  1. "Generate JavaScript array method examples: map, filter, forEach, push, pop with explanations"
  2. "Create a JavaScript object tutorial with examples of nested objects and arrays"
  3. "Write exercises that compare array methods (map vs forEach, push vs concat)"

Starter Code

// 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
}

Final Code

// 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);

Exercises

  1. Create an array of 5 numbers. Use map to double each number and filter to keep only numbers greater than 10.
  2. Create an object representing a book with title, author, pages, and genres (array). Access the second genre.
  3. Write code that removes duplicate values from an array using filter and indexOf.

Homework

  1. Create a to-do list application using arrays and objects. Each task should be an object with a text property and a completed boolean.
  2. Research JavaScript array methods: find the difference between map and forEach. Write a summary.

Quiz

  1. Which array method returns a new array with transformed elements?
    • A) forEach
    • B) map ✅
    • C) filter
    • D) push

    Answer: B

  2. What does array.push() return?
    • A) The new element
    • B) The new array length ✅
    • C) The modified array
    • D) undefined

    Answer: B

  3. How do you access the property "name" of object user?
    • A) user.name
    • B) user["name"]
    • C) Both A and B ✅
    • D) user->name

    Answer: C

  4. Which method removes the last element from an array?
    • A) array.pop() ✅
    • B) array.shift()
    • C) array.remove()
    • D) array.delete()

    Answer: A

  5. What does array.filter() return?
    • A) A new array with elements that pass the test ✅
    • B) The first matching element
    • C) The number of matching elements
    • D) A boolean

    Answer: A

← Back to Module README