CSC 200 — JavaScript Lecture Notes Dept.
of Computer Science
CSC 200
Frontend Development — JavaScript
Comprehensive Lecture Notes & Practicals
01 Variables & Data Types 02 Functions & Scope
03 Arrays & Objects 04 DOM Manipulation
05 Events & Listeners 06 ES6+ Features
07 Async/Await & Promises 08 Fetch API / AJAX
Department of Computer Science | Academic Session 2025/2026
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
SECTION 01 Foundation
Variables & Data Types
A variable is a named container that stores a value. Think of it like a labelled box — you place
something inside, give it a name, and reference it whenever you need it. JavaScript gives us three
keywords to declare variables: var, let, and const.
1.1 Declaration Keywords
Analogy
var → Writing on a public whiteboard. Anyone in the building can erase or overwrite it.
let → A personal notebook. Only editable inside the current room (block) you are in.
const → A laminated ID card. Set once; cannot be changed or re-assigned.
Keyword Behaviour
var Function-scoped. Hoisted to top of function. Avoid in modern JS.
let Block-scoped. Can be re-assigned. Preferred for changeable values.
const Block-scoped. Cannot be re-assigned. Use for all values that must
not change.
1.2 Data Types
JavaScript is a dynamically typed language — you do not declare the type explicitly; the engine
infers it at runtime. The seven primitive types are:
• String — textual data: "Hello" or 'World' or `template ${name}`
• Number — integers and decimals: 42, 3.14, -7
• Boolean — logical true / false only
• Undefined — a variable declared but not yet given a value
• Null — an intentional empty/absent value (typeof returns 'object' — a known JS quirk)
• Symbol — a unique, immutable identifier (ES6+, advanced)
• BigInt — arbitrarily large integers: 9007199254740991n
1.3 Code Examples
// Declaring variables
let studentName = 'Amara'; // String
let age = 21; // Number
let isEnrolled = true; // Boolean
const MAX_SCORE = 100; // Constant number
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
let result; // Undefined (not yet set)
// Template literals (ES6)
let greeting = `Hello, ${studentName}! You are ${age} years old.`;
[Link](greeting);
// typeof operator reveals the type
[Link](typeof age); // 'number'
[Link](typeof isEnrolled); // 'boolean'
[Link](typeof null); // 'object' <-- JS quirk!
Key Rule
Prefer const by default. Switch to let only when you know the value will change.
Never use var — it has confusing scoping rules that lead to hard-to-find bugs.
EXERCISE 1 Variables in Practice
In your code editor (or browser console), write the following:
1. Declare three const variables: your name, your department, and the current year.
2. Declare a let variable called score and set it to 0. Then reassign it to 75.
3. Use a template literal to print a sentence combining all four variables.
4. Use typeof to check and print the type of each variable.
5. Bonus: Try re-assigning a const variable. What error do you get and why?
Write your answer in the space below or in your code editor.
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
SECTION 02 Logic
Functions & Scope
A function is a reusable block of code designed to perform a specific task. You define it once, then
call it as many times as needed. Functions are first-class citizens in JavaScript — they can be
stored in variables, passed as arguments, and returned from other functions.
2.1 Defining Functions
// 1. Function Declaration (hoisted — can be called before its definition)
function greet(name) {
return `Welcome, ${name}!`;
}
// 2. Function Expression (not hoisted)
const add = function(a, b) {
return a + b;
};
// 3. Arrow Function (ES6 — concise syntax)
const multiply = (a, b) => a * b;
// 4. Default Parameters (ES6)
const greetUser = (name = 'Student') => `Hello, ${name}!`;
[Link](greet('Chidi')); // Welcome, Chidi!
[Link](add(10, 5)); // 15
[Link](multiply(4, 3)); // 12
[Link](greetUser()); // Hello, Student!
2.2 Scope
Scope determines where a variable is accessible. JavaScript has three levels of scope:
• Global Scope — declared outside any function; accessible everywhere
• Function Scope — declared inside a function; only accessible inside that function
• Block Scope — declared inside { } with let or const; only accessible within that block
let globalVar = 'I am global'; // Global scope
function demonstrateScope() {
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
let functionVar = 'I am function-scoped';
if (true) {
let blockVar = 'I am block-scoped';
[Link](globalVar); // OK
[Link](functionVar); // OK
[Link](blockVar); // OK
}
// [Link](blockVar); // ERROR: blockVar is not defined
}
// [Link](functionVar); // ERROR: out of scope
2.3 Closures (Conceptual Introduction)
A closure is when an inner function remembers variables from its outer function even after the outer
function has finished running. This is a powerful — and frequently tested — JavaScript feature.
function makeCounter() {
let count = 0; // outer variable
return function() { // inner function (closure)
count++;
return count;
};
}
const counter = makeCounter();
[Link](counter()); // 1
[Link](counter()); // 2
[Link](counter()); // 3 — count persists!
EXERCISE 2 Functions & Scope
Write JavaScript functions to solve the following problems:
1. Write a function called square(n) that returns the square of a number.
2. Write an arrow function called isEven(n) that returns true if the number is even.
3. Write a function gradeStudent(score) that returns 'A' (70+), 'B' (60+), 'C' (50+), or 'F'.
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
4. Create a function called makeMultiplier(x) that returns a function which multiplies any number
by x. Test it: makeMultiplier(5)(3) should return 15.
5. Bonus: Explain in a comment what scope each variable belongs to in your makeMultiplier
solution.
Write your answer in the space below or in your code editor.
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
SECTION 03 Data Structures
Arrays & Objects
Arrays and objects are JavaScript's primary data structures. Arrays store ordered lists of values;
objects store key-value pairs that describe a thing. Both are used extensively in every real-world
JavaScript application.
3.1 Arrays
const courses = ['Mathematics', 'CSC200', 'Physics', 'English'];
// Accessing elements (zero-indexed)
[Link](courses[0]); // 'Mathematics'
[Link]([Link]); // 4
// Common array methods
[Link]('Chemistry'); // Add to end
[Link](); // Remove from end
[Link]('Biology'); // Add to beginning
[Link](); // Remove from beginning
// Iterating
[Link](course => [Link](course));
// Transforming — map returns a NEW array
const upper = [Link](c => [Link]());
// Filtering — filter returns items that pass the test
const cscOnly = [Link](c => [Link]('CSC'));
// Reducing — reduce collapses array to a single value
const scores = [70, 85, 60, 90];
const total = [Link]((sum, val) => sum + val, 0); // 305
3.2 Objects
// Object literal
const student = {
name: 'Amara Obi',
matric: 'CSC/2023/001',
level: 200,
isActive: true,
courses: ['Math', 'CSC200'],
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
// Method inside an object
introduce() {
return `Hi, I am ${[Link]}, ${[Link]} level.`;
}
};
// Accessing properties
[Link]([Link]); // dot notation
[Link](student['matric']); // bracket notation
[Link]([Link]());
// Destructuring (ES6) — pull properties into variables
const { name, level } = student;
[Link](name, level); // Amara Obi 200
// Spread operator — shallow copy or merge
const updatedStudent = { ...student, level: 300 };
EXERCISE 3 Arrays & Objects
Work with the following data structure or create your own:
1. Create an array of at least 5 student names. Print the first and last name using indexing.
2. Use .map() to create a new array where each name is prefixed with 'Student: '.
3. Use .filter() to return only names longer than 5 characters.
4. Create an object representing yourself with at least 5 properties (include an array as one
property).
5. Write a method inside the object that returns a formatted introduction string using this.
6. Bonus: Use [Link]() and [Link]() on your object and print the results.
Write your answer in the space below or in your code editor.
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
SECTION 04 Browser Interaction
DOM Manipulation
The Document Object Model (DOM) is a tree representation of an HTML page that JavaScript can
read and modify. When you change the DOM, the browser immediately re-renders the visible page.
This is how dynamic websites work.
Analogy
Think of the DOM as a family tree of your HTML elements. The <html> tag is the great-
grandparent.
Every <div>, <p>, <button> is a node in this tree. JavaScript lets you find any node,
change its content, move it, remove it, or create brand new nodes — all without reloading the
page.
4.1 Selecting Elements
// Single element selectors
const title = [Link]('main-title');
const firstBtn = [Link]('.btn'); // CSS selector — first
match
// Multiple element selectors
const allBtns = [Link]('.btn'); // NodeList of all
matches
const listItems = [Link]('li');
4.2 Modifying Elements
const heading = [Link]('h1');
// Changing content
[Link] = 'New Heading Text'; // plain text
[Link] = '<em>Italic Heading</em>'; // with HTML tags
// Changing styles
[Link] = 'blue';
[Link] = '32px';
// Changing CSS classes
[Link]('highlight');
[Link]('old-class');
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
[Link]('active'); // adds if absent, removes if
present
// Changing attributes
const link = [Link]('a');
[Link]('href', '[Link]
[Link]([Link]('href'));
4.3 Creating & Removing Elements
// Create a new element
const newParagraph = [Link]('p');
[Link] = 'This paragraph was added by JavaScript!';
[Link]('dynamic-content');
// Append it to an existing element
[Link](newParagraph);
// Insert before another element
const list = [Link]('ul');
const newItem = [Link]('li');
[Link] = 'New list item';
[Link](newItem, [Link]);
// Remove an element
const toRemove = [Link]('.old-item');
[Link]();
EXERCISE 4 DOM Manipulation
Create an HTML file with a heading, a paragraph, a button, and an unordered list. Then write a
script that:
1. Selects the heading and changes its text to 'CSC 200 — Live DOM Demo'.
2. Changes the heading colour to your department's colour using JavaScript.
3. Selects the paragraph and appends the current date/time to its text content.
4. Creates three new <li> items and appends them to the unordered list.
5. Adds a class 'active' to the button when the page loads.
6. Bonus: Use querySelectorAll to select all list items and change their colour to purple.
Write your answer in the space below or in your code editor.
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
SECTION 05 Interactivity
Events & Event Listeners
An event is anything that happens in the browser — a button click, a key press, a mouse movement,
a form submission, the page loading. Event listeners are functions that wait for a specific event and
run when it occurs. This is the foundation of interactivity.
5.1 The addEventListener Method
// Syntax: [Link](eventType, callbackFunction);
const button = [Link]('#myBtn');
// Anonymous function
[Link]('click', function() {
[Link]('Button was clicked!');
});
// Named function (cleaner, reusable, removable)
function handleClick() {
[Link]('Button clicked via named function');
}
[Link]('click', handleClick);
// Arrow function
[Link]('click', () => {
[Link] = 'lightblue';
});
5.2 The Event Object
Every event handler receives an event object (often written as e or event). It carries useful
information about what happened.
[Link]('keydown', function(e) {
[Link]('Key pressed:', [Link]); // e.g. 'Enter'
[Link]('Key code:', [Link]); // e.g. 'Enter'
if ([Link] === 'Enter') {
[Link]('Enter key detected!');
}
});
// Form submission — prevent default browser behaviour
const form = [Link]('form');
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
[Link]('submit', function(e) {
[Link](); // Stops the page from reloading
[Link]('Form submitted via JavaScript!');
});
// Mouse events — get cursor coordinates
[Link]('mousemove', (e) => {
[Link](`X: ${[Link]}, Y: ${[Link]}`);
});
5.3 Common Event Types
Event Fires when...
click User clicks an element
dblclick User double-clicks an element
keydown / keyup A keyboard key is pressed / released
input Input field value changes (every keystroke)
change Input field loses focus after a value change
submit A form is submitted
mouseover / mouseout Mouse enters / leaves an element
DOMContentLoaded HTML has fully loaded and parsed
load Page and all resources (images etc.) have loaded
EXERCISE 5 Events & Listeners
Extend your HTML file from Section 4 or create a new one with a form containing a text input and
a button:
1. Add a click listener on the button that displays an alert with the input's current value.
2. Add a keydown listener on the input: print each key pressed to the console.
3. Add a mouseover listener on the heading: change its background colour when hovered.
4. Add a submit listener on the form that prevents default and instead logs 'Form handled by JS'.
5. Bonus: Add a DOMContentLoaded listener that sets the input's placeholder to today's date.
Write your answer in the space below or in your code editor.
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
SECTION 06 Modern JavaScript
ES6+ Features
ES6 (ECMAScript 2015) and later versions introduced powerful features that make JavaScript
cleaner, shorter, and more expressive. Mastery of these features is expected in any professional or
academic context today.
6.1 Destructuring
// Array destructuring
const [first, second, ...rest] = [10, 20, 30, 40, 50];
[Link](first); // 10
[Link](rest); // [30, 40, 50]
// Object destructuring
const { name, age, department = 'CSC' } = { name: 'Bola', age: 22 };
[Link](name); // 'Bola'
[Link](department); // 'CSC' (default value)
// Destructuring in function parameters
function displayStudent({ name, level }) {
return `${name} is in level ${level}`;
}
6.2 Spread & Rest Operators
// Spread — expand an iterable into individual elements
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a:1, b:2, c:3 }
// Rest — collect remaining arguments into an array
function sum(...numbers) { // numbers is an array
return [Link]((total, n) => total + n, 0);
}
[Link](sum(1, 2, 3, 4, 5)); // 15
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
6.3 Modules (import / export)
// [Link] — named exports
export const PI = 3.14159;
export function square(n) { return n * n; }
export function cube(n) { return n * n * n; }
// Default export
export default function greet(name) { return `Hello, ${name}`; }
// [Link] — importing
import greet, { PI, square } from './[Link]';
[Link](PI); // 3.14159
[Link](square(4)); // 16
[Link](greet('Amara')); // Hello, Amara
Quick Reference — ES6+ Features
Arrow functions: const fn = (x) => x * 2;
Template literals: `Hello, ${name}!`
Default params: function greet(name = 'World') {}
Destructuring: const { a, b } = obj;
Spread operator: const copy = [...original];
Rest params: function sum(...args) {}
Optional chaining: user?.address?.city (ES2020)
Nullish coalescing: value ?? 'default' (ES2020)
EXERCISE 6 ES6+ Modernisation
Refactor old-style code or write new code using ES6+ features:
1. Convert this function to an arrow function: function add(a, b) { return a + b; }
2. Use destructuring to extract name, age, and matric from a student object in one line.
3. Write a rest-parameter function called average(...nums) that returns the average of any
number of arguments.
4. Create two arrays of your top 3 courses and top 3 hobbies. Combine them into one array
using spread.
5. Use optional chaining to safely access user?.profile?.bio and print it (test with an undefined
user).
6. Bonus: Create a small module (two files) that exports a utility function and imports/uses it.
Write your answer in the space below or in your code editor.
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
SECTION 07 Asynchronous JavaScript
Async/Await & Promises
JavaScript is single-threaded — it can only do one thing at a time. But many operations (reading a
file, calling an API, waiting for a timer) take time. Asynchronous JavaScript allows those operations
to happen in the background while the rest of the code keeps running.
Analogy
You walk into a restaurant and place an order. You do not stand frozen at the counter waiting.
You go sit down (continue executing code). When your food is ready, the waiter brings it to you
(the callback fires / the promise resolves). That is asynchronous behaviour.
7.1 Promises
A Promise is an object representing the eventual success or failure of an async operation. It has
three states: pending, fulfilled, or rejected.
// Creating a promise
const fetchData = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve('Data loaded successfully!'); // fulfilled
} else {
reject('Something went wrong.'); // rejected
}
});
// Consuming a promise
fetchData
.then(data => [Link](data)) // runs on resolve
.catch(err => [Link](err)) // runs on reject
.finally(() => [Link]('Done')); // always runs
7.2 Async / Await
async/await is syntactic sugar over promises. It makes asynchronous code look and behave like
synchronous code — far more readable.
// Simulated API call (returns a promise after 1 second)
function simulateAPI() {
return new Promise(resolve => {
setTimeout(() => resolve({ user: 'Amara', score: 92 }), 1000);
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
});
}
// async function — always returns a promise
async function loadUserData() {
try {
[Link]('Loading...');
const data = await simulateAPI(); // pauses here until resolved
[Link]('User:', [Link]);
[Link]('Score:', [Link]);
} catch (error) {
[Link]('Error:', error);
}
}
loadUserData();
7.3 Promise Utilities
// [Link] — run multiple promises in parallel, wait for ALL
const p1 = fetch('/api/users');
const p2 = fetch('/api/posts');
const [users, posts] = await [Link]([p1, p2]);
// [Link] — resolves/rejects with the FIRST settled promise
const fastest = await [Link]([p1, p2]);
// [Link] — waits for ALL, regardless of success or failure
const results = await [Link]([p1, p2]);
[Link](r => [Link]([Link], [Link] ?? [Link]));
EXERCISE 7 Promises & Async/Await
Practice asynchronous JavaScript with the following:
1. Create a function delay(ms) that returns a promise resolving after ms milliseconds (use
setTimeout).
2. Write an async function that calls delay(2000), then logs 'Done waiting!' after 2 seconds.
3. Create a promise that randomly resolves or rejects. Handle both outcomes with .then()
and .catch().
4. Write an async function with a try/catch block that calls the random promise from task 3.
5. Bonus: Use [Link] to run three delay() calls of different durations simultaneously. Log
the time taken vs running them sequentially.
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
Write your answer in the space below or in your code editor.
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
SECTION 08 Network Requests
Fetch API / AJAX
AJAX (Asynchronous JavaScript and XML) is a technique for making HTTP requests from the
browser without reloading the page. The modern approach uses the built-in Fetch API, which
returns promises and works seamlessly with async/await.
8.1 Basic GET Request
// Fetch returns a promise that resolves to a Response object
async function getUsers() {
try {
const response = await
fetch('[Link]
// Check if the request was successful (status 200-299)
if (![Link]) {
throw new Error(`HTTP error: ${[Link]}`);
}
const users = await [Link](); // parse JSON body
[Link](users);
return users;
} catch (error) {
[Link]('Fetch failed:', [Link]);
}
}
getUsers();
8.2 POST Request (Sending Data)
async function createPost(postData) {
const response = await fetch('[Link] {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: [Link](postData), // convert object to JSON string
});
const newPost = await [Link]();
[Link]('Created:', newPost);
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
createPost({
title: 'My First Post',
body: 'Hello from JavaScript!',
userId: 1,
});
8.3 Rendering API Data to the DOM
async function displayUsers() {
const users = await getUsers();
const list = [Link]('#user-list');
[Link](0, 5).forEach(user => {
const li = [Link]('li');
[Link] = `${[Link]} — ${[Link]}`;
[Link](li);
});
}
[Link]('DOMContentLoaded', displayUsers);
EXERCISE 8 Fetch API — Mini Project
Use the free public API at [Link] to complete the following:
1. Fetch the list of posts from /posts and log the title of each post.
2. Fetch a single post using /posts/1 and display its title and body on an HTML page.
3. Fetch the list of users from /users. Create a <ul> in HTML and render each user as an <li>
showing their name and email.
4. Add a text input and a button. When the button is clicked, fetch the post matching the entered
ID (e.g. /posts/3) and display it.
5. Bonus: Add loading state text ('Loading...') before the fetch starts and remove it when done.
Handle errors by showing an error message on the page.
Write your answer in the space below or in your code editor.
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
Quick Reference Sheet
Use this page as a cheat-sheet during revision or lab sessions.
Variable Declaration
const name = 'value'; // immutable binding
let count = 0; // mutable binding, block-scoped
Arrow Function Forms
const fn1 = x => x * 2; // single param, implicit return
const fn2 = (x, y) => x + y; // multiple params
const fn3 = (x) => { const r = x * 2; return r; }; // block body, explicit
return
Array Methods Summary
Method What it does
[Link](val) Adds val to end of array
[Link]() Removes and returns last element
[Link](fn) Returns new array of fn(each element)
[Link](fn) Returns new array of elements where fn returns true
[Link](fn, init) Reduces array to single value
[Link](fn) Returns first element where fn returns true
[Link](fn) Returns true if any element passes fn
[Link](fn) Returns true if all elements pass fn
[Link](val) Returns true if val is in the array
[Link](val) Returns index of val (-1 if not found)
Fetch API Pattern
async function fetchJSON(url) {
const res = await fetch(url);
if (![Link]) throw new Error([Link]);
return [Link]();
}
Academic Session 2025/2026 Page
CSC 200 — JavaScript Lecture Notes Dept. of Computer Science
Academic Integrity Reminder
All exercises and practical assessments must represent your own original work.
Collaboration is encouraged for understanding; submitted solutions must be independently
written.
Reference any external resources (MDN, Stack Overflow) used during your research.
Academic Session 2025/2026 Page