Week 4 Day 3 JavaScript Lesson:
👋 Warm Greeting
"Hey my awesome campers! 🌞
Welcome back to our JavaScript jungle! 🏕️ Today, we’re exploring a magical tool in our coder’s toolbox — something that lets our code talk to other code, hand over tasks, and say: 'Here, you handle this for me when you’re ready.'
It’s called a callback function — and by the end of this lesson, you’ll see why callbacks are one of the most important concepts in JavaScript. let’s go! 🚶♂️🌳
1. What is a Callback Function?
A callback function is simply:
In plain English:
Think of callbacks like giving your friend a phone number before you go into a meeting.
You’re telling them:
They don’t call you immediately — they call you when the cooking is done.
That’s exactly how callbacks work.
Basic Syntax
Here:
greet is the callback.
processUserInput is the function that receives the callback and calls it later.
2. Why Use Callbacks?
We use callbacks when:
➤We want to wait for something to finish (e.g., user input, data loading, timer, file download).
➤We want code to be flexible (you can pass in different behavior without changing the original function).
💡 Think of callbacks as "fill in the blank" in a plan — the main function has the structure, and the callback decides the specific action.
3. Analogy — Ethiopian Coffee Ceremony ☕
Imagine you are attending an Ethiopian coffee ceremony.
You sit down and the host says:
“Tell me what snack you want, and I’ll bring it when the coffee is ready.”
You give your snack choice — that’s your callback.
The host prepares coffee (main function), and when it’s ready, they call your function (bring your snack).
4. Synchronous vs Asynchronous Callbacks
Synchronous callback
Happens immediately during the function execution.
Output:
Asynchronous callback
Happens later (after some time/event).
Output:
Here, setTimeout is like saying:
5. Callbacks with Parameters
We can pass data into callbacks just like normal functions.
6. Anonymous Callbacks
Instead of naming the callback, you can pass it directly as an anonymous function.
Or with arrow functions:
✅ Summary
➤A callback is a function passed into another function.
➤It can be synchronous or asynchronous.
➤Great for flexibility and waiting for tasks to finish.
➤Can be named, anonymous, or arrow functions.
👋 Warm Greeting
"Hey my awesome campers! 🌞
Welcome back to our JavaScript jungle! 🏕️ Today, we’re exploring a magical tool in our coder’s toolbox — something that lets our code talk to other code, hand over tasks, and say: 'Here, you handle this for me when you’re ready.'
It’s called a callback function — and by the end of this lesson, you’ll see why callbacks are one of the most important concepts in JavaScript. let’s go! 🚶♂️🌳
1. What is a Callback Function?
A callback function is simply:
A function that is passed as an argument to another function, and that other function can call it (or “invoke” it) later.
In plain English:
Think of callbacks like giving your friend a phone number before you go into a meeting.
You’re telling them:
“When you finish cooking, call me on this number so I know it’s ready.” 📞
They don’t call you immediately — they call you when the cooking is done.
That’s exactly how callbacks work.
Basic Syntax
function greet(name) {
console.log(Hello, ${name}!); }
function processUserInput(callback) {
let name = prompt("Please enter your name:");
callback(name); // Call the function passed in }
processUserInput(greet);
Here:
greet is the callback.
processUserInput is the function that receives the callback and calls it later.
2. Why Use Callbacks?
We use callbacks when:
➤We want to wait for something to finish (e.g., user input, data loading, timer, file download).
➤We want code to be flexible (you can pass in different behavior without changing the original function).
💡 Think of callbacks as "fill in the blank" in a plan — the main function has the structure, and the callback decides the specific action.
3. Analogy — Ethiopian Coffee Ceremony ☕
Imagine you are attending an Ethiopian coffee ceremony.
You sit down and the host says:
“Tell me what snack you want, and I’ll bring it when the coffee is ready.”
You give your snack choice — that’s your callback.
The host prepares coffee (main function), and when it’s ready, they call your function (bring your snack).
4. Synchronous vs Asynchronous Callbacks
Synchronous callback
Happens immediately during the function execution.
function sayHello() {
console.log("Hello!"); }
function runImmediately(callback) {
callback(); // Runs now }
runImmediately(sayHello);
console.log("This runs after sayHello"); Output:
Hello!
This runs after sayHello Asynchronous callback
Happens later (after some time/event).
function showDone() {
console.log("Timer finished!"); }
console.log("Timer started..."); setTimeout(showDone, 2000); // Wait 2 seconds Output:
Timer started...
(2 seconds later) Timer finished! Here, setTimeout is like saying:
“When the timer finishes, call this function.”
5. Callbacks with Parameters
We can pass data into callbacks just like normal functions.
function printSquare(num) {
console.log(num * num); }
function doMath(num, callback) {
callback(num); }
doMath(5, printSquare); // Output: 25 6. Anonymous Callbacks
Instead of naming the callback, you can pass it directly as an anonymous function.
setTimeout(function () {
console.log("Anonymous callback says hi!"); }, 1000); Or with arrow functions:
setTimeout(() => { console.log("Arrow function callback here!"); }, 1000);✅ Summary
➤A callback is a function passed into another function.
➤It can be synchronous or asynchronous.
➤Great for flexibility and waiting for tasks to finish.
➤Can be named, anonymous, or arrow functions.
challengeCodes.js
4.6 KB
Week 3 extra challenges
Week 4 day 1
Week 4 day 2
Week 4 day 1
Week 4 day 2
🔥Week 4 Day 3 Callback Challenges
1. Mood Tracker with Callback
What to do:
Ask the user for their mood for today, then use a callback function to display a custom message based on the mood they entered.
Hint:
Make one function to collect the mood, and another function (the callback) to decide what message to show.
Example moods: "happy", "sad", "mehh".
2. Custom Greeting Machine
What to do:
Write a function that takes a name and a callback. The callback will decide how to greet the person — formal, funny, or casual.
Hint:
Test it with three different callbacks to see how the same function can behave differently.
Example greetings: "Hello Mr. …", "Yo …", "Good day, …".
3. Simple Math Processor
What to do:
Make a function that takes two numbers and a callback. The callback can decide to add, subtract, multiply, or divide them.
Hint:
Write four different callbacks for the four operations and try passing each one.
4. Random Joke Teller
What to do:
Make a function that picks a random joke from an array and pass it to another function (callback) that displays it in a special way — for example, uppercase, decorated, or with emojis.
Hint:
Use Math.floor(Math.random() * array.length) to pick a joke.
🎯 Your Mission Campers:
➤Pick any three of these challenges, solve them using what we’ve learned, and push yourself to be creative with the callbacks.
➤When you’re done, share your work with the group,
➤ invite more friends to join the camp, and as always…
Stay curious, Stay coding andddd Stay well ✌️
1. Mood Tracker with Callback
What to do:
Ask the user for their mood for today, then use a callback function to display a custom message based on the mood they entered.
Hint:
Make one function to collect the mood, and another function (the callback) to decide what message to show.
Example moods: "happy", "sad", "mehh".
2. Custom Greeting Machine
What to do:
Write a function that takes a name and a callback. The callback will decide how to greet the person — formal, funny, or casual.
Hint:
Test it with three different callbacks to see how the same function can behave differently.
Example greetings: "Hello Mr. …", "Yo …", "Good day, …".
3. Simple Math Processor
What to do:
Make a function that takes two numbers and a callback. The callback can decide to add, subtract, multiply, or divide them.
Hint:
Write four different callbacks for the four operations and try passing each one.
4. Random Joke Teller
What to do:
Make a function that picks a random joke from an array and pass it to another function (callback) that displays it in a special way — for example, uppercase, decorated, or with emojis.
Hint:
Use Math.floor(Math.random() * array.length) to pick a joke.
🎯 Your Mission Campers:
➤Pick any three of these challenges, solve them using what we’ve learned, and push yourself to be creative with the callbacks.
➤When you’re done, share your work with the group,
➤ invite more friends to join the camp, and as always…
Stay curious, Stay coding andddd Stay well ✌️
Week 4 Day 4 JavaScript lesson
👋 Hey there, my awesome campers!
Today, we’re diving into one of the most important building blocks in JavaScript:
✅Objects and
✅the mysterious keyword this.
By the end of today, you’ll be able to make your code more organized, reusable, and real-world-ready.
1️⃣ What is an Object?
In JavaScript, objects are like containers for storing related data and functionality together in key–value pairs.
Keys → the names (like labels).
Values → the actual data (can be strings, numbers, arrays, functions… even other objects!).
📦 Analogy:
Think of an object like a basket with different compartments:
➤One holds injera (string value)
➤Another holds wot (number for quantity)
➤Another holds berbere (array for spice levels)
➤And another holds a cooking method (function).
Instead of carrying separate baskets for each thing, you keep them together in one basket — that’s exactly how objects group related stuff.
Example:
2️⃣ Creating Objects
We can create objects in two main ways:
1. Object literal (most common)
2. Using the new Object() constructor (less common for beginners)
3️⃣ Adding, Changing, and Removing Properties
4️⃣ Methods (Functions inside Objects)
When a function lives inside an object, we call it a method.
5️⃣ The Special Keyword: this
What is this?
this is a special keyword that refers to the object that is currently using the method.
📦 Analogy: Imagine each basket has its own “name tag.” When you say “this basket’s injera,” you mean the injera inside the current basket you’re holding — not any other basket.
Example:
Here, this.name looks inside the object that called the method (in this case, user).
⚠️ Important Note about this
If you use arrow functions inside objects, this behaves differently — it does not bind to the object, it takes this from the surrounding scope.
Example:
Why? Because arrow functions don’t create their own this.
For methods, always use the regular function() syntax.
6️⃣ Real-World Example:
This is how objects + this help model real-world systems like banks, shops, games, etc.
🌟 Summary:
✅Objects store related data and functions together.
✅Keys and values make objects flexible.
✅Methods are functions inside objects.
✅this refers to the object that owns the method.
✅Use function() for object methods (not arrow functions) if you need this.
👋 Hey there, my awesome campers!
Today, we’re diving into one of the most important building blocks in JavaScript:
✅Objects and
✅the mysterious keyword this.
By the end of today, you’ll be able to make your code more organized, reusable, and real-world-ready.
1️⃣ What is an Object?
In JavaScript, objects are like containers for storing related data and functionality together in key–value pairs.
Keys → the names (like labels).
Values → the actual data (can be strings, numbers, arrays, functions… even other objects!).
📦 Analogy:
Think of an object like a basket with different compartments:
➤One holds injera (string value)
➤Another holds wot (number for quantity)
➤Another holds berbere (array for spice levels)
➤And another holds a cooking method (function).
Instead of carrying separate baskets for each thing, you keep them together in one basket — that’s exactly how objects group related stuff.
Example:
let student = {
name: "Abebe",
age: 18,
skills: ["JavaScript", "HTML", "CSS"],
greet: function() {
console.log("Hello! My name is " + this.name); } };
console.log(student.name); // Access property: "Abebe"
console.log(student.skills[1]); // Access array inside object: "HTML"
student.greet(); // Call method: "Hello! My name is Abebe" 2️⃣ Creating Objects
We can create objects in two main ways:
1. Object literal (most common)
let car = {
brand: "Toyota",
year: 2020 }; 2. Using the new Object() constructor (less common for beginners)
let car = new Object();
car.brand = "Toyota";
car.year = 2020; 3️⃣ Adding, Changing, and Removing Properties
let person = {
name: "Almaz",
age: 25 };
person.job = "Teacher"; // Add new property
person.age = 26; // Change value
delete person.name; // Remove property
console.log(person); 4️⃣ Methods (Functions inside Objects)
When a function lives inside an object, we call it a method.
let dog = {
name: "Bingo",
bark: function() {
console.log("Woof! Woof!"); } };
dog.bark(); // "Woof! Woof!"
5️⃣ The Special Keyword: this
What is this?
this is a special keyword that refers to the object that is currently using the method.
📦 Analogy: Imagine each basket has its own “name tag.” When you say “this basket’s injera,” you mean the injera inside the current basket you’re holding — not any other basket.
Example:
let user = {
name: "Sara",
greet: function() {
console.log("Hi, I'm " + this.name); } };
user.greet(); // "Hi, I'm Sara" Here, this.name looks inside the object that called the method (in this case, user).
⚠️ Important Note about this
If you use arrow functions inside objects, this behaves differently — it does not bind to the object, it takes this from the surrounding scope.
Example:
let user = {
name: "Kebede",
greet: () => { console.log("Hi, I'm " + this.name); } };
user.greet(); // "Hi, I'm undefined" 😬
Why? Because arrow functions don’t create their own this.
For methods, always use the regular function() syntax.
6️⃣ Real-World Example:
let bankAccount = {
owner: "Mekdes",
balance: 5000,
deposit: function(amount) {
this.balance += amount;
console.log(${this.owner} deposited ${amount} birr. New balance: ${this.balance}); },
withdraw: function(amount) {
if (amount <= this.balance) {
this.balance -= amount;
console.log(${this.owner} withdrew ${amount} birr. Remaining balance: ${this.balance}); }
else { console.log("Insufficient funds!"); } } };
bankAccount.deposit(1000); bankAccount.withdraw(2000);
This is how objects + this help model real-world systems like banks, shops, games, etc.
🌟 Summary:
✅Objects store related data and functions together.
✅Keys and values make objects flexible.
✅Methods are functions inside objects.
✅this refers to the object that owns the method.
✅Use function() for object methods (not arrow functions) if you need this.
Assignment
➤objects
https://youtu.be/lo7o91qLzxc?si=JNrFWZgMs-qn0AMW
➤this
https://youtu.be/Jdlo8ZDt5Jg?si=T3ahEgR7cbkW0pe9
➤objects
https://youtu.be/lo7o91qLzxc?si=JNrFWZgMs-qn0AMW
➤this
https://youtu.be/Jdlo8ZDt5Jg?si=T3ahEgR7cbkW0pe9
YouTube
Learn JavaScript OBJECTS in 7 minutes! 🧍
#JavaScript #tutorial #course
// object = A collection of related properties and/or methods
// Can represent real world objects (people, products, places)
// object = {key:value,
// function()}…
// object = A collection of related properties and/or methods
// Can represent real world objects (people, products, places)
// object = {key:value,
// function()}…
💥💥 Week 4 Day 4 Challenges
Hey campers! 👋 Hope you’re all doing great and ready to flex your JavaScript muscles.
Today’s challenges are all about objects and this, putting our new skills into action.
1️⃣ Student Grade Tracker
Create an object that stores student names and their scores.
➤Add a method to add a score.
➤Add a method to get the average score.
➤Add a method to find the highest scorer.
💡 Hint: Store students in an array as objects like { name: "Abel", score: 89 }. Use loops to process the data.
2️⃣ Contact Book Lite
Make an object that stores people’s names and phone numbers.
➤Add a contact.
➤Delete a contact.
➤Show all contacts.
💡 Hint: Use an array to store multiple contact objects. Example: { name: "Marta", phone: "0912345678" }.
3️⃣ Simple Shopping Cart
Build an object representing a shopping cart.
➤Add an item with name and price.
➤Remove an item by name.
➤Show the total price.
💡 Hint: Items can be stored in an array as objects: { name: "Bread", price: 15 }. Loop through to get the total.
4️⃣ Movie Watchlist
An object that keeps a list of movies to watch.
➤Add a movie title.
➤Mark as watched.
➤Show all watched movies.
💡 Hint: Each movie can be stored as { title: "Avatar", watched: false }. When marking as watched, update the property to true.
✅ Your mission:
▶️Choose any 3 challenges from today’s list and bring them to life using objects and this.
After you’re done,
✅ share your creations,
✅ invite your friends to join our camp, and as always —
stay awesome and code on! ✌️
Hey campers! 👋 Hope you’re all doing great and ready to flex your JavaScript muscles.
Today’s challenges are all about objects and this, putting our new skills into action.
1️⃣ Student Grade Tracker
Create an object that stores student names and their scores.
➤Add a method to add a score.
➤Add a method to get the average score.
➤Add a method to find the highest scorer.
💡 Hint: Store students in an array as objects like { name: "Abel", score: 89 }. Use loops to process the data.
2️⃣ Contact Book Lite
Make an object that stores people’s names and phone numbers.
➤Add a contact.
➤Delete a contact.
➤Show all contacts.
💡 Hint: Use an array to store multiple contact objects. Example: { name: "Marta", phone: "0912345678" }.
3️⃣ Simple Shopping Cart
Build an object representing a shopping cart.
➤Add an item with name and price.
➤Remove an item by name.
➤Show the total price.
💡 Hint: Items can be stored in an array as objects: { name: "Bread", price: 15 }. Loop through to get the total.
4️⃣ Movie Watchlist
An object that keeps a list of movies to watch.
➤Add a movie title.
➤Mark as watched.
➤Show all watched movies.
💡 Hint: Each movie can be stored as { title: "Avatar", watched: false }. When marking as watched, update the property to true.
✅ Your mission:
▶️Choose any 3 challenges from today’s list and bring them to life using objects and this.
After you’re done,
✅ share your creations,
✅ invite your friends to join our camp, and as always —
stay awesome and code on! ✌️
📅 Week 4 — Day 5 JavaScript OOP Basics:
Constructors, new, Prototypes, Inheritance & ES6 Classes
Hey hey, brilliant campers! 👋🌞
Grab your ☕ and settle in—today we level up from “using objects” to designing them. By the end, you’ll know how to build your own blueprints for data and behavior, share methods efficiently, and create families of related objects. This is the foundation of building real apps.
1) Why OOP? (Quick intuition)
Think of building many similar things:
➤A Student with name,grade,age, and methods like introduce() ,takeExam(), playFootball(),or getAverage().
➤A Product with price, discount logic, etc.
You don’t want to copy-paste the same object structure again and again. You want a blueprint you can reuse to make many instances. That’s OOP.
Key words you’ll see:
✅Class / Constructor → the blueprint
✅Instance → an object created from the blueprint
✅Method → a function that lives on the object
✅Prototype → where shared methods live (saves memory!)
✅Inheritance → one blueprint building on another
2) Constructor Functions (Pre‑class style)
Before ES6 classes, JavaScript used constructor functions to act like blueprints. Now it's changed. But let's look what it was like since they are very related.
2.1 Defining a constructor
By convention, constructor names are Capitalized.
2.2 Creating instances with new
3) What does new actually do?
When you write new Person("Abebe", 20) JavaScript does:
➤Create a new empty object: {}
➤Link that object to Person.prototype
➤Bind this inside Person to the new object
➤Return the object automatically
If you forget new, this won’t point to a new object—bugs ensue.
4) Prototypes: where shared methods live
If you put methods inside the constructor, each instance gets its own copy (wasteful). Instead, attach methods to the prototype so all instances share one function.
4.1 Property lookup (prototype chain)
When you call a.greet():
➥JS looks for greet on a
➥If not found, it looks on Person.prototype
➥If still not found, it looks on Object.prototype
➥…until it either finds it or gives undefined
5) Inheritance with Constructor Functions
Let’s say a Student is a specialized Person.
5.1 Borrow the Person constructor for shared properties
5.2 Link prototypes so methods are inherited
5.3 Use it
That’s classic JavaScript inheritance before classes.
Constructors, new, Prototypes, Inheritance & ES6 Classes
Hey hey, brilliant campers! 👋🌞
Grab your ☕ and settle in—today we level up from “using objects” to designing them. By the end, you’ll know how to build your own blueprints for data and behavior, share methods efficiently, and create families of related objects. This is the foundation of building real apps.
1) Why OOP? (Quick intuition)
Think of building many similar things:
➤A Student with name,grade,age, and methods like introduce() ,takeExam(), playFootball(),or getAverage().
➤A Product with price, discount logic, etc.
You don’t want to copy-paste the same object structure again and again. You want a blueprint you can reuse to make many instances. That’s OOP.
Key words you’ll see:
✅Class / Constructor → the blueprint
✅Instance → an object created from the blueprint
✅Method → a function that lives on the object
✅Prototype → where shared methods live (saves memory!)
✅Inheritance → one blueprint building on another
2) Constructor Functions (Pre‑class style)
Before ES6 classes, JavaScript used constructor functions to act like blueprints. Now it's changed. But let's look what it was like since they are very related.
2.1 Defining a constructor
By convention, constructor names are Capitalized.
function Person(name, age) {
this.name = name; // instance property
this.age = age; // instance property // ❌ Avoid defining methods here (explained below) }
2.2 Creating instances with new
const p1 = new Person("Abebe", 20);
const p2 = new Person("Saba", 22);
console.log(p1.name); // "Abebe"
console.log(p2.age); // 22
3) What does new actually do?
When you write new Person("Abebe", 20) JavaScript does:
➤Create a new empty object: {}
➤Link that object to Person.prototype
➤Bind this inside Person to the new object
➤Return the object automatically
If you forget new, this won’t point to a new object—bugs ensue.
4) Prototypes: where shared methods live
If you put methods inside the constructor, each instance gets its own copy (wasteful). Instead, attach methods to the prototype so all instances share one function.
function Person(name, age) {
this.name = name;
this.age = age; } // Shared by all Person instances
Person.prototype.greet = function () {
console.log(Hi, I'm ${this.name} and I'm ${this.age}.); };
const a = new Person("Almaz", 25);
const b = new Person("Kebede", 30);
a.greet(); // "Hi, I'm Almaz and I'm 25."
b.greet(); // "Hi, I'm Kebede and I'm 30."
console.log(a.greet === b.greet); // true ✅ (one shared function)
4.1 Property lookup (prototype chain)
When you call a.greet():
➥JS looks for greet on a
➥If not found, it looks on Person.prototype
➥If still not found, it looks on Object.prototype
➥…until it either finds it or gives undefined
5) Inheritance with Constructor Functions
Let’s say a Student is a specialized Person.
5.1 Borrow the Person constructor for shared properties
function Student(name, age, major) {
Person.call(this, name, age); // call Person with this instance
this.major = major; }
5.2 Link prototypes so methods are inherited
Student.prototype = Object.create(Person.prototype); // inherit
Student.prototype.constructor = Student; // fix constructor pointer
Student.prototype.study = function () {
console.log(${this.name} is studying ${this.major}.); };
5.3 Use it
const s = new Student("Mahi", 19, "Computer Science");
s.greet(); // from Person.prototype s.study(); // from Student.prototype
That’s classic JavaScript inheritance before classes.
6) ES6 Classes (Modern, cleaner syntax)
Now we use ES6 classes which are syntax sugar over prototypes. The behavior is the same; the code is cleaner.
6.1 Basic class with constructor and methods
6.2 Inheritance with extends and super
We can make a new class that inherits from another.
6.3 Getters, setters, and static methods (handy basics)
➤setters and getters allow controlled access properties. For example , using set we can prevent the user from entering a number for names.
➥getter/setter make property-style reads/writes that run code under the hood.
➥static methods are utilities on the class itself (not on instances).
7) this inside classes and methods (quick reminder)
➥In class methods and prototype methods, this refers to the instance that called the method.
➥Avoid using arrow functions for prototype methods when you need dynamic this. Arrow functions capture this from the outer scope, which can surprise you.
8) Real‑World Mini Example :Library with Books (composition + classes)
9) Common Pitfalls (and fixes)
➤Forgetting new with constructor functions:
➤Defining methods inside the constructor (duplicates for each instance). Prefer prototypes or class methods.
➤Arrow functions as class/prototype methods when you expect dynamic this. Use regular methods unless you need lexical binding.
➤Forgetting to reset constructor after Object.create in old‑style inheritance:
Now we use ES6 classes which are syntax sugar over prototypes. The behavior is the same; the code is cleaner.
6.1 Basic class with constructor and methods
class Person {
constructor(name, age) {
this.name = name; // instance property
this.age = age; } // methods go on the prototype (shared)
greet() { console.log(Hi, I'm ${this.name} and I'm ${this.age}.); } }
const p = new Person("Betelhem", 21); p.greet();
Under the hood, greet is still placed on Person.prototype.
6.2 Inheritance with extends and super
We can make a new class that inherits from another.
class Student extends Person {
constructor(name, age, major) {
super(name, age); // call Person constructor
this.major = major; }
study() {
console.log(${this.name} is studying ${this.major}.); } }
const st = new Student("Samuel", 20, "Math");
st.greet(); // inherited
st.study(); // own method
6.3 Getters, setters, and static methods (handy basics)
➤setters and getters allow controlled access properties. For example , using set we can prevent the user from entering a number for names.
class BankAccount {
constructor(owner, balance = 0) {
this.owner = owner;
this._balance = balance; // convention: underscore = "internal" }
// Getter (access like a property)
get balance() {
return this._balance; }
// Setter (validate on assignment)
set balance(value) {
if (value < 0) {
console.log("Balance cannot be negative.");
return; }
this._balance = value; }
deposit(amount) {
this._balance += amount; }
withdraw(amount) {
if (amount > this._balance) {
console.log("Insufficient funds!"); return; }
this._balance -= amount; }
// Static method (belongs to the class, not instances)
static compare(a, b) {
return a.balance - b.balance; } }
const a1 = new BankAccount("Hanna", 1000);
const a2 = new BankAccount("Abel", 500);
a1.deposit(200);
console.log(a1.balance); // getter a1.balance = 50; // setter console.log(BankAccount.compare(a1, a2)); // static ➥getter/setter make property-style reads/writes that run code under the hood.
➥static methods are utilities on the class itself (not on instances).
7) this inside classes and methods (quick reminder)
➥In class methods and prototype methods, this refers to the instance that called the method.
➥Avoid using arrow functions for prototype methods when you need dynamic this. Arrow functions capture this from the outer scope, which can surprise you.
class Demo {
constructor(name) {
this.name = name; }
sayName() { // good console.log(this.name); }
sayNameArrow = () => {
// fine for fields, butthisis lexically bound console.log(this.name); } }
8) Real‑World Mini Example :Library with Books (composition + classes)
class Book {
constructor(title, author, pages) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = false; }
markRead() {
this.read = true; } }
class Library {
constructor(name) {
this.name = name;
this.collection = []; // array of Book instances }
addBook(book) {
this.collection.push(book); }
listUnread() {
return this.collection.filter(b => !b.read); }
}
const b1 = new Book("Javascript Essentials", "Sara", 220);
const b2 = new Book("CSS Mastery", "Almaz", 180);
const lib = new Library("Addis Tech Library");
lib.addBook(b1);
lib.addBook(b2);
b1.markRead(); console.log(lib.listUnread().map(b => b.title)); 9) Common Pitfalls (and fixes)
➤Forgetting new with constructor functions:
➤Defining methods inside the constructor (duplicates for each instance). Prefer prototypes or class methods.
➤Arrow functions as class/prototype methods when you expect dynamic this. Use regular methods unless you need lexical binding.
➤Forgetting to reset constructor after Object.create in old‑style inheritance:
Assignment
➤constructors
https://youtu.be/WPmAu26LZKo?si=QoSME94Qnk6A6uVp
➤classes
https://youtu.be/U2vxAEiaVRY?si=sjfL7XzYJ4_RGojL
➤inheritance
https://youtu.be/DqUPa0D2N78?si=lwm9omb9U7qSLwUj
➤super
https://youtu.be/Cto38GpvJgg?si=KH98Uf_FvcXpnIdY
➤setters and getters
https://youtu.be/KQVCAnh6Afk?si=9lgyffcxOFC9CwNI
➤constructors
https://youtu.be/WPmAu26LZKo?si=QoSME94Qnk6A6uVp
➤classes
https://youtu.be/U2vxAEiaVRY?si=sjfL7XzYJ4_RGojL
➤inheritance
https://youtu.be/DqUPa0D2N78?si=lwm9omb9U7qSLwUj
➤super
https://youtu.be/Cto38GpvJgg?si=KH98Uf_FvcXpnIdY
➤setters and getters
https://youtu.be/KQVCAnh6Afk?si=9lgyffcxOFC9CwNI
YouTube
JavaScript CONSTRUCTORS in 5 minutes! 🛠
#JavaScript #tutorial #course
// constructor = special method for defining the
// properties and methods of objects
function Car(make, model, year, color){
this.make = make,
this.model = model,
this.year = year,
…
// constructor = special method for defining the
// properties and methods of objects
function Car(make, model, year, color){
this.make = make,
this.model = model,
this.year = year,
…
💥💥Week 4 Day 5 — OOP Challenges
Hey Campers 👋, you’ve now entered the world of Object-Oriented Programming. Today’s challenges are all about practicing classes, objects, and inheritance.
👉 Here are 6 challenge ideas — choose any 3 that excite you most.
1. 🎓 School System Lite
➤Create a Student class with properties like name, age, and grade.
➤Add methods like study() and introduce().
➤Create a Teacher class that inherits from a Person class and has an extra method teach().
💡 Hint: Use extends to inherit, and remember to call super() inside your constructor.
2. 📒 Contact Book OOP
➤Make a Contact class with name, phone, and email.
➤Create a ContactBook class to manage many contacts.
➤Add methods like addContact(), removeContact(), and listContacts().
💡 Hint: Store contacts in an array inside ContactBook.
3. 🛒 Shopping Cart Pro
➤Create a Product class with name and price.
➤Build a Cart class to addProduct(), removeProduct(), and calculateTotal().
➤Add a price validation using getters and setters.
4. 🎬 Movie Watchlist OOP
➤Create a Movie class with title, genre, and watched.
➤Add a method toggleWatched() to switch watched status.
➤Create a Watchlist class to manage multiple movies.
💡 Hint: Add a listUnwatched() method for extra fun.
5. 🏦 ATM Simulation
➤Create a BankAccount class with owner and balance.
➤Add methods deposit(), withdraw(), and checkBalance().
➤Prevent withdrawing more than available balance.
💡 Hint: Use conditionals inside your withdraw() method.
6. 🚗 Transport System
➤Make a Vehicle class with brand and speed.
➤Add methods like drive() and stop().
➤Extend it into Car and Bus classes, each with its own style of drive().
✨ Now it’s your turn! Choose any 3 challenges and start building.
Remember:
▶️Share your solutions 🖥️
▶️Invite friends to join the fun 👭
▶️Stay well, stay curious, and stay coding! ✌️🔥
Hey Campers 👋, you’ve now entered the world of Object-Oriented Programming. Today’s challenges are all about practicing classes, objects, and inheritance.
👉 Here are 6 challenge ideas — choose any 3 that excite you most.
1. 🎓 School System Lite
➤Create a Student class with properties like name, age, and grade.
➤Add methods like study() and introduce().
➤Create a Teacher class that inherits from a Person class and has an extra method teach().
💡 Hint: Use extends to inherit, and remember to call super() inside your constructor.
2. 📒 Contact Book OOP
➤Make a Contact class with name, phone, and email.
➤Create a ContactBook class to manage many contacts.
➤Add methods like addContact(), removeContact(), and listContacts().
💡 Hint: Store contacts in an array inside ContactBook.
3. 🛒 Shopping Cart Pro
➤Create a Product class with name and price.
➤Build a Cart class to addProduct(), removeProduct(), and calculateTotal().
➤Add a price validation using getters and setters.
4. 🎬 Movie Watchlist OOP
➤Create a Movie class with title, genre, and watched.
➤Add a method toggleWatched() to switch watched status.
➤Create a Watchlist class to manage multiple movies.
💡 Hint: Add a listUnwatched() method for extra fun.
5. 🏦 ATM Simulation
➤Create a BankAccount class with owner and balance.
➤Add methods deposit(), withdraw(), and checkBalance().
➤Prevent withdrawing more than available balance.
💡 Hint: Use conditionals inside your withdraw() method.
6. 🚗 Transport System
➤Make a Vehicle class with brand and speed.
➤Add methods like drive() and stop().
➤Extend it into Car and Bus classes, each with its own style of drive().
✨ Now it’s your turn! Choose any 3 challenges and start building.
Remember:
▶️Share your solutions 🖥️
▶️Invite friends to join the fun 👭
▶️Stay well, stay curious, and stay coding! ✌️🔥
🌟 Week 4 Day 6 — Introduction to the DOM
👋 Hello my awesome campers!
Welcome back to another exciting session. You’ve been doing amazing with JavaScript so far. Up until now, most of the things we did lived inside the console — we logged messages, built little games, tracked moods, handled functions, closures, and even dived into OOP.
But let’s be honest… if we only live in the console forever, it’s kinda boring, right? 😅
The real fun of JavaScript is making web pages alive — adding interactivity, changing text, moving things, and responding to what the user does.
👉 That’s where DOM comes in.
🏗️ What is the DOM?
DOM stands for Document Object Model.
Sounds scary? Let’s break it down:
➤Document → this means your HTML page.
➤Object Model → your browser takes that HTML and turns it into an object-like structure that JavaScript can understand.
➤Think of your web page like a family tree 🌳:
➥At the very top, you have the document (the root).
➥Inside, you have children: <html>, <head>, <body>.
➥Inside <body> you have more children: <h1>, <p>, <div>, <button>, etc.
➥And inside them, maybe even more children!
So the DOM is basically a map of your page that JavaScript can walk through and change.
🔍 Example: HTML and its DOM
Now, the DOM is how JavaScript sees this page.
The browser turns it into a tree like this:
🛠️ Accessing the DOM with JavaScript
To work with the DOM, we use the global object document.
Think of document as the "doorway" into the HTML page.
Example 1: Select by ID
👉 Output: <h1 id="title">Hello Campers!</h1>
We grabbed the <h1> element from the page.
Example 2: Select by Class
👉 Output: an HTMLCollection with <p class="message">Welcome to the world of DOM.</p>
Example 3: Select by Tag Name
👉 Output: an HTMLCollection with all <button> elements.
Example 4: Modern Query Selector
And if you want all matches:
✍️ Changing the DOM
Cool, now we don’t just want to find elements — we want to change them!
1. Change Text
👉 This replaces the <h1> text.
2. Change HTML Inside
👉 Puts bold text inside the paragraph.
3. Change Styles
👉 Makes the heading big and blue.
4. Add or Remove Classes
👋 Hello my awesome campers!
Welcome back to another exciting session. You’ve been doing amazing with JavaScript so far. Up until now, most of the things we did lived inside the console — we logged messages, built little games, tracked moods, handled functions, closures, and even dived into OOP.
But let’s be honest… if we only live in the console forever, it’s kinda boring, right? 😅
The real fun of JavaScript is making web pages alive — adding interactivity, changing text, moving things, and responding to what the user does.
👉 That’s where DOM comes in.
🏗️ What is the DOM?
DOM stands for Document Object Model.
Sounds scary? Let’s break it down:
➤Document → this means your HTML page.
➤Object Model → your browser takes that HTML and turns it into an object-like structure that JavaScript can understand.
➤Think of your web page like a family tree 🌳:
➥At the very top, you have the document (the root).
➥Inside, you have children: <html>, <head>, <body>.
➥Inside <body> you have more children: <h1>, <p>, <div>, <button>, etc.
➥And inside them, maybe even more children!
So the DOM is basically a map of your page that JavaScript can walk through and change.
🔍 Example: HTML and its DOM
<!DOCTYPE html>
<html>
<head>
<title>My First DOM Page</title>
</head>
<body>
<h1 id="title">Hello Campers!</h1>
<p class="message">Welcome to the world of DOM.</p>
<button>Click Me!</button>
</body>
</html> Now, the DOM is how JavaScript sees this page.
The browser turns it into a tree like this:
Document
└── html
├── head │
└── title → "My First DOM Page"
└── body
├── h1#title → "Hello Campers!"
├── p.message → "Welcome to the world of DOM."
└── button → "Click Me!"
🛠️ Accessing the DOM with JavaScript
To work with the DOM, we use the global object document.
Think of document as the "doorway" into the HTML page.
Example 1: Select by ID
let heading = document.getElementById("title");
console.log(heading); 👉 Output: <h1 id="title">Hello Campers!</h1>
We grabbed the <h1> element from the page.
Example 2: Select by Class
let message = document.getElementsByClassName("message");
console.log(message); 👉 Output: an HTMLCollection with <p class="message">Welcome to the world of DOM.</p>
Example 3: Select by Tag Name
let buttons = document.getElementsByTagName("button");
console.log(buttons); 👉 Output: an HTMLCollection with all <button> elements.
Example 4: Modern Query Selector
let heading = document.querySelector("#title"); // first match
let paragraph = document.querySelector(".message"); // first element with class "message"
let button = document.querySelector("button"); // first <button> And if you want all matches:
let allButtons = document.querySelectorAll("button");
console.log(allButtons);
✍️ Changing the DOM
Cool, now we don’t just want to find elements — we want to change them!
1. Change Text
let heading = document.getElementById("title");
heading.textContent = "Hello JavaScript World!"; 👉 This replaces the <h1> text.
2. Change HTML Inside
paragraph.innerHTML = "<strong>DOM is powerful!</strong>"; 👉 Puts bold text inside the paragraph.
3. Change Styles
heading.style.color = "blue";
heading.style.fontSize = "50px"; 👉 Makes the heading big and blue.
4. Add or Remove Classes
heading.classList.add("highlight");
heading.classList.remove("highlight");🎯 Real Life Example
Imagine you have a scoreboard in a game:
JavaScript can make it dynamic:
Now every time the button is clicked → score goes up. 🎉
🤔 Why is DOM Important?
Without DOM:
➤Your page would just sit there, lifeless 🪦.
With DOM:
➤You can create games, interactive forms, todo lists, dynamic shopping carts, quizzes, and basically any modern website feature.
DOM = JavaScript + HTML + CSS working together.
🌟 Wrap Up
Today we learned:
✅ DOM = Document Object Model (a tree of your page).
✅ document object lets JS access and control HTML.
✅ Ways to select elements: ➥getElementById, ➥getElementsByClassName, ➥getElementsByTagName, ➥querySelector, querySelectorAll.
✅ Ways to change DOM: textContent, innerHTML, style, classList.
✅ Why DOM makes web pages interactive.
We’ll dive deeper into events and more DOM manipulation tricks in the coming days.
Imagine you have a scoreboard in a game:
<h2 id="score">Score: 0</h2>
<button id="increase">Increase</button>
JavaScript can make it dynamic:
let score = 0;
let scoreBoard = document.getElementById("score");
let btn = document.getElementById("increase");
btn.addEventListener("click", function() {
score += 1;
scoreBoard.textContent = "Score: " + score; }); Now every time the button is clicked → score goes up. 🎉
🤔 Why is DOM Important?
Without DOM:
➤Your page would just sit there, lifeless 🪦.
With DOM:
➤You can create games, interactive forms, todo lists, dynamic shopping carts, quizzes, and basically any modern website feature.
DOM = JavaScript + HTML + CSS working together.
🌟 Wrap Up
Today we learned:
✅ DOM = Document Object Model (a tree of your page).
✅ document object lets JS access and control HTML.
✅ Ways to select elements: ➥getElementById, ➥getElementsByClassName, ➥getElementsByTagName, ➥querySelector, querySelectorAll.
✅ Ways to change DOM: textContent, innerHTML, style, classList.
✅ Why DOM makes web pages interactive.
We’ll dive deeper into events and more DOM manipulation tricks in the coming days.
💥💥 Week 4 Day 6 — DOM Challenges
Choose any 3 of the following:
1. 🏫 Student Roster Formatter
You’re given a list of student names inside <ul>.
Task: Loop through all <li> items and make them uppercase.
Hint: Use getElementsByTagName or querySelectorAll and a for loop.
2. 📚 Quote of the Day
Have an empty <p id="quote"> on your page.
Task: Store 5 quotes in an array. Select one at random and display it in the <p>.
Hint: Use Math.random() and .textContent.
3. 🎨 Rainbow Paragraphs
You have several <p> elements on the page.
Task: Give each one a different color from an array of colors (["red", "orange", "green", "blue", "purple"]).
Hint: Loop and use .style.color.
4. 🎭 Identity Switcher
Suppose your page has <h1 id="title">Welcome</h1> and <p id="desc">This is a page</p>.
Task: Swap their contents (the <h1> text becomes the <p> text and vice versa).
5. 🌍 Language Translator Lite
You have <p id="greet">Hello</p>.
Task: Create an array of greetings (["Hola", "Bonjour", "Ciao", "Hallo"]) and make the <p> cycle through them one by one when the script runs.
✅ Wrap Up
👉 Choose any 3 challenges.
👉 Use everything you’ve learned so far: loops, arrays, objects, and DOM properties (.textContent, .style, etc.).
👉 And as always:
share,
invite,
stay curious, and stay coding ✌️
Choose any 3 of the following:
1. 🏫 Student Roster Formatter
You’re given a list of student names inside <ul>.
Task: Loop through all <li> items and make them uppercase.
Hint: Use getElementsByTagName or querySelectorAll and a for loop.
2. 📚 Quote of the Day
Have an empty <p id="quote"> on your page.
Task: Store 5 quotes in an array. Select one at random and display it in the <p>.
Hint: Use Math.random() and .textContent.
3. 🎨 Rainbow Paragraphs
You have several <p> elements on the page.
Task: Give each one a different color from an array of colors (["red", "orange", "green", "blue", "purple"]).
Hint: Loop and use .style.color.
4. 🎭 Identity Switcher
Suppose your page has <h1 id="title">Welcome</h1> and <p id="desc">This is a page</p>.
Task: Swap their contents (the <h1> text becomes the <p> text and vice versa).
5. 🌍 Language Translator Lite
You have <p id="greet">Hello</p>.
Task: Create an array of greetings (["Hola", "Bonjour", "Ciao", "Hallo"]) and make the <p> cycle through them one by one when the script runs.
✅ Wrap Up
👉 Choose any 3 challenges.
👉 Use everything you’ve learned so far: loops, arrays, objects, and DOM properties (.textContent, .style, etc.).
👉 And as always:
share,
invite,
stay curious, and stay coding ✌️
🌞 Week 4 — Day 7: DOM Events & Dynamic Elements (Deep deep Dive!)
Hey amazing campers 👋😄
You’ve met the DOM and learned how to select elements and change them. Today we’ll make pages come alive with events (clicks, typing, submitting, mouse moves…) and learn how to create, insert, and remove elements with JavaScript. This is the moment JS starts to feel magical. ✨
0) Quick mental model: what’s an “event”?
An event is something that happens in (or to) the page: a button is clicked, a user types in a field, a form is submitted, an image finishes loading, etc.
We can listen for that event and then run code in response. That’s interactivity.
1) Two ways to listen for events
A) The old way (inline or property)
Inline in HTML (not recommended):
Property on element (okay for quick demos):
❗ Limitation: Only one onclick can exist at a time; assigning a new one overwrites the old.
B) The modern way (recommended): addEventListener
✅ You can attach multiple listeners, remove them later, and choose options (like capture/once/passive).
To remove a listener, you need the same function reference:
2) The event object (event / e)
When an event happens, the browser gives you an event object with details about it.
3) Common, super-useful events
A) click
B) input vs change (text fields, selects)
input fires on every keystroke (live updates).
change fires when the element loses focus or the selection finalizes.
C) submit (forms) + preventing reload
Forms submit by default (page reload). Stop that with event.preventDefault().
D) Keyboard events: keydown, keyup
E) Mouse events: mouseover / mouseout / mousemove
Hey amazing campers 👋😄
You’ve met the DOM and learned how to select elements and change them. Today we’ll make pages come alive with events (clicks, typing, submitting, mouse moves…) and learn how to create, insert, and remove elements with JavaScript. This is the moment JS starts to feel magical. ✨
0) Quick mental model: what’s an “event”?
An event is something that happens in (or to) the page: a button is clicked, a user types in a field, a form is submitted, an image finishes loading, etc.
We can listen for that event and then run code in response. That’s interactivity.
1) Two ways to listen for events
A) The old way (inline or property)
Inline in HTML (not recommended):
<button onclick="alert('Clicked!')">Click me</button> Property on element (okay for quick demos):
const btn = document.getElementById('myBtn'); btn.onclick = function () { console.log('Clicked!'); }; ❗ Limitation: Only one onclick can exist at a time; assigning a new one overwrites the old.
B) The modern way (recommended): addEventListener
const btn = document.getElementById('myBtn');
function handleClick() {
console.log('Clicked!'); }
btn.addEventListener('click', handleClick); ✅ You can attach multiple listeners, remove them later, and choose options (like capture/once/passive).
To remove a listener, you need the same function reference:
btn.removeEventListener('click', handleClick); 2) The event object (event / e)
When an event happens, the browser gives you an event object with details about it.
document.addEventListener('click', function (e) {
console.log('Type:', e.type); // "click"
console.log('Target:', e.target); // the element that was clicked
console.log('Coordinates:', e.clientX, e.clientY); }); 3) Common, super-useful events
A) click
<button id="likeBtn">👍 Like</button>
<p id="count">0</p>
<script>
const likeBtn = document.getElementById('likeBtn');
const out = document.getElementById('count');
let likes = 0;
likeBtn.addEventListener('click', () => {
likes += 1;
out.textContent = likes; });
</script> B) input vs change (text fields, selects)
input fires on every keystroke (live updates).
change fires when the element loses focus or the selection finalizes.
<input id="nameField" placeholder="Type your name..." />
<p id="preview"></p>
<script>
const nameField = document.getElementById('nameField');
const preview = document.getElementById('preview');
nameField.addEventListener('input', () => {
preview.textContent =Hello, ${nameField.value || 'stranger'}!; });
</script>
C) submit (forms) + preventing reload
Forms submit by default (page reload). Stop that with event.preventDefault().
<form id="loginForm">
<input name="user" placeholder="Username" required />
<input name="pass" type="password" placeholder="Password" required />
<button>Log in</button>
</form>
<p id="msg"></p>
<script> const form = document.getElementById('loginForm');
const msg = document.getElementById('msg');
form.addEventListener('submit', (e) => {
e.preventDefault(); // stop page reload
const user = form.user.value;
const pass = form.pass.value;
msg.textContent =Trying to log in as: ${user} (password length: ${pass.length}); });
</script>
D) Keyboard events: keydown, keyup
<input id="command" placeholder="Type then press Enter" />
<p id="result"></p>
<script>
const command = document.getElementById('command');
const result = document.getElementById('result');
command.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { result.textContent =You entered: ${command.value}; } });
</script>
E) Mouse events: mouseover / mouseout / mousemove
<div id="box" style="width:200px;height:120px;background:#eef;border:1px solid #99f;">
</div>
<p id="coord"></p>
<script>
const box = document.getElementById('box');
const coord = document.getElementById('coord');
box.addEventListener('mousemove', (e) => {
coord.textContent =x: ${e.offsetX}, y: ${e.offsetY}; });
</script>
F) Focus events: focus / blur
4) Event Bubbling, Capturing & Delegation (beginner-friendly)
Bubbling & Capturing (just enough to use)
When you click a child element, the event travels:
➤Capturing: from document → down to the target.
➤Bubbling: from the target → back up to document (this is the default most people use).
➤addEventListener(type, handler, options):
➤{ capture: true } makes the handler run on the capturing phase.
➤{ once: true } runs the handler only once.
➤{ passive: true } tells the browser the handler won’t call preventDefault() (useful for scroll).
Event Delegation (powerful & simple)
Attach one listener to a parent and handle many children based on e.target.
✅ Works even if you later add more <li>s—one listener handles all.
5) Creating & inserting elements (the dynamic DOM)
A) createElement, set content/attrs, then insert
B) append, prepend, before, after, insertBefore
C) Removing elements: element.remove() or parent.removeChild(child)
D) Cloning nodes: cloneNode
E) innerHTML vs textContent (safety & speed)
➤textContent → sets text only (safe; shows <b> as text).
➤innerHTML → parses as HTML (powerful, but never put untrusted user input here—XSS risk).
6) Managing classes & styles cleanly
A) classList
B) Inline styles vs CSS classes
Prefer toggling classes (cleaner). Inline styles are fine for quick demos:
7) Attributes, properties, and dataset
A) getAttribute / setAttribute
<input id="email" placeholder="Email" />
<p id="hint"></p>
<script>
const email = document.getElementById('email');
const hint = document.getElementById('hint');
email.addEventListener('focus', () => hint.textContent = 'Format: name@example.com');
email.addEventListener('blur', () => hint.textContent = '');
</script> 4) Event Bubbling, Capturing & Delegation (beginner-friendly)
Bubbling & Capturing (just enough to use)
When you click a child element, the event travels:
➤Capturing: from document → down to the target.
➤Bubbling: from the target → back up to document (this is the default most people use).
➤addEventListener(type, handler, options):
➤{ capture: true } makes the handler run on the capturing phase.
➤{ once: true } runs the handler only once.
➤{ passive: true } tells the browser the handler won’t call preventDefault() (useful for scroll).
Event Delegation (powerful & simple)
Attach one listener to a parent and handle many children based on e.target.
<ul id="menu">
<li data-action="home">Home</li>
<li data-action="about">About</li>
<li data-action="contact">Contact</li>
</ul>
<p id="out"></p>
<script>
const menu = document.getElementById('menu');
const out = document.getElementById('out');
menu.addEventListener('click', (e) => {
if (e.target.matches('li')) {
const action = e.target.dataset.action; // from data-action
out.textContent =You clicked: ${action}; } });
</script>
✅ Works even if you later add more <li>s—one listener handles all.
5) Creating & inserting elements (the dynamic DOM)
A) createElement, set content/attrs, then insert
<ul id="todos"></ul>
<script>
const todos = document.getElementById('todos');
const li = document.createElement('li');
li.textContent = 'Learn DOM';
li.setAttribute('data-priority', 'high');
todos.appendChild(li); // insert as last child
</script> B) append, prepend, before, after, insertBefore
<div id="wrap">
<p>First</p>
</div>
<script>
const wrap = document.getElementById('wrap');
const p1 = document.createElement('p');
p1.textContent = 'Appended at end';
wrap.append(p1);
const p2 = document.createElement('p');
p2.textContent = 'Prepended at start';
wrap.prepend(p2);
const outsideTop = document.createElement('p');
outsideTop.textContent = 'Before the wrapper';
wrap.before(outsideTop);
const outsideBottom = document.createElement('p');
outsideBottom.textContent = 'After the wrapper';
wrap.after(outsideBottom);
</script> C) Removing elements: element.remove() or parent.removeChild(child)
const item = document.querySelector('#todos li');
item.remove(); // easy way
// or old-school:
const parent = document.getElementById('todos');
const first = parent.firstElementChild;
parent.removeChild(first); D) Cloning nodes: cloneNode
const original = document.querySelector('#todos li');
const copy = original.cloneNode(true); // true = deep clone (children too)
original.after(copy); E) innerHTML vs textContent (safety & speed)
➤textContent → sets text only (safe; shows <b> as text).
➤innerHTML → parses as HTML (powerful, but never put untrusted user input here—XSS risk).
const box = document.getElementById('box');
box.textContent = '<b>hello</b>'; // shows literally <b>hello</b>
box.innerHTML = '<b>hello</b>'; // renders bold hello 6) Managing classes & styles cleanly
A) classList
const card = document.getElementById('card');
card.classList.add('active');
card.classList.remove('hidden');
card.classList.toggle('highlight'); // add if missing, remove if present
const hasIt = card.classList.contains('active'); B) Inline styles vs CSS classes
Prefer toggling classes (cleaner). Inline styles are fine for quick demos:
card.style.backgroundColor = 'lightyellow';
card.style.border = '1px solid #ccc'; 7) Attributes, properties, and dataset
A) getAttribute / setAttribute
const link = document.querySelector('a');
link.setAttribute('href', 'https://example.com');
console.log(link.getAttribute('href'));
B) Properties (often nicer)
C) Custom data: data-* + dataset
8) Forms + validation basics (DOM side)
✅ Uses built-in HTML validation + DOM for feedback.
9) When should your JS run? (DOMContentLoaded, defer)
Option A: Put <script> at the end of <body>
HTML loads first → then script runs (elements exist).
Option B: Use defer in the head
defer waits until HTML is parsed, then runs script.
Option C: Listen for the DOM to be ready
10) Mini build (step-by-step): Add items to a list + remove items
(Just a teaching demo; not a “challenge”)
What you practiced here:
➤submit + preventDefault()
➤createElement / appendChild / append
➤event.target and delegation on the <ul>
11) Good habits & small gotchas
✅Prefer addEventListener over inline events.
✅Use textContent for text; innerHTML only when you must render HTML (never with untrusted input).
✅Prefer classes (classList) over inline styles.
✅Use defer or run code after DOMContentLoaded.
✅When attaching many handlers to many children, prefer event delegation on their parent.
✅Keep HTML semantic & accessible (use <button> for clickables, connect <label> with for to inputs, etc.).
🧠 Today you learned
✅The right way to handle events with addEventListener (and how to remove them).
✅The event object and how to use event.target.
✅The difference between input / change / submit / keyboard & mouse events.
✅Creating, inserting, cloning, and removing elements.
✅classList, attributes vs properties, and custom data- attributes.
✅How to organize scripts so the DOM exists when your code runs.
🔥🔥You just unlocked the power to build real interactive pages. 🚀
const img = document.querySelector('img');
img.src = 'cat.jpg';
img.alt = 'A cute cat'; C) Custom data: data-* + dataset
<button id="pay" data-plan="pro" data-price="299">Buy</button>
<script>
const pay = document.getElementById('pay');
console.log(pay.dataset.plan); // "pro"
console.log(pay.dataset.price); // "299"
</script> 8) Forms + validation basics (DOM side)
<form id="signup">
<input id="email" type="email" placeholder="Email" required />
<input id="pwd" type="password" placeholder="Password (min 6)" minlength="6" required />
<button>Sign Up</button>
</form>
<p id="status"></p>
<script>
const form = document.getElementById('signup');
const status = document.getElementById('status');
form.addEventListener('submit', (e) => {
e.preventDefault(); if (!form.checkValidity()) {
status.textContent = 'Please fix form errors.'; return; }
const email = document.getElementById('email').value;
status.textContent =Welcome, ${email}!; });
</script>
✅ Uses built-in HTML validation + DOM for feedback.
9) When should your JS run? (DOMContentLoaded, defer)
Option A: Put <script> at the end of <body>
HTML loads first → then script runs (elements exist).
Option B: Use defer in the head
<script src="app.js" defer></script> defer waits until HTML is parsed, then runs script.
Option C: Listen for the DOM to be ready
document.addEventListener('DOMContentLoaded', () => {
// safe to query and manipulate the DOM here }); 10) Mini build (step-by-step): Add items to a list + remove items
(Just a teaching demo; not a “challenge”)
<form id="todoForm">
<input id="todoInput" placeholder="New task..." />
<button>Add</button>
</form>
<ul id="todoList"></ul>
<script>
const form = document.getElementById('todoForm');
const input = document.getElementById('todoInput');
const list = document.getElementById('todoList');
form.addEventListener('submit', (e) => {
e.preventDefault();
const text = input.value.trim();
if (!text) return; // 1) create
const li = document.createElement('li');
li.textContent = text + ' ';
// remove button
const removeBtn = document.createElement('button');
removeBtn.textContent = '✖'; removeBtn.setAttribute('aria-label', 'Remove item');
li.append(removeBtn);
// 2) insert
list.appendChild(li);
// 3) clear input
input.value = ''; });
// Event delegation to remove items
list.addEventListener('click', (e) => {
if (e.target.tagName === 'BUTTON') {
e.target.parentElement.remove(); } });
</script> What you practiced here:
➤submit + preventDefault()
➤createElement / appendChild / append
➤event.target and delegation on the <ul>
11) Good habits & small gotchas
✅Prefer addEventListener over inline events.
✅Use textContent for text; innerHTML only when you must render HTML (never with untrusted input).
✅Prefer classes (classList) over inline styles.
✅Use defer or run code after DOMContentLoaded.
✅When attaching many handlers to many children, prefer event delegation on their parent.
✅Keep HTML semantic & accessible (use <button> for clickables, connect <label> with for to inputs, etc.).
🧠 Today you learned
✅The right way to handle events with addEventListener (and how to remove them).
✅The event object and how to use event.target.
✅The difference between input / change / submit / keyboard & mouse events.
✅Creating, inserting, cloning, and removing elements.
✅classList, attributes vs properties, and custom data- attributes.
✅How to organize scripts so the DOM exists when your code runs.
🔥🔥You just unlocked the power to build real interactive pages. 🚀
Assignment :
➤Add/Change html
https://youtu.be/WCRi7y6aNrQ?si=JkZyU_xqa5BzUksy
➤mouse events
https://youtu.be/g_vXSKbfUiQ?si=JiJzcKuj6O7pWNRP
➤key events
https://youtu.be/q32skvBgxo4?si=lc80uMObuZ-HUpTl
➤Hide/show
https://youtu.be/MkvHPOT4RS8?si=Zxre1aDV9tMPyzwr
➤Add/Change html
https://youtu.be/WCRi7y6aNrQ?si=JkZyU_xqa5BzUksy
➤mouse events
https://youtu.be/g_vXSKbfUiQ?si=JiJzcKuj6O7pWNRP
➤key events
https://youtu.be/q32skvBgxo4?si=lc80uMObuZ-HUpTl
➤Hide/show
https://youtu.be/MkvHPOT4RS8?si=Zxre1aDV9tMPyzwr
YouTube
How to ADD/CHANGE HTML using JavaScript 🛠️
#JavaScript #html #tutorial
00:00:00 setup
00:01:10 h1 element
00:09:32 list items
// STEP 1 CREATE THE ELEMENT
const newH1 = document.createElement("h1");
// STEP 2 ADD ATTRIBUTES/PROPERTIES
newH1.textContent = "I like pizza!";
newH1.id = "myH1";
newH1.style.color…
00:00:00 setup
00:01:10 h1 element
00:09:32 list items
// STEP 1 CREATE THE ELEMENT
const newH1 = document.createElement("h1");
// STEP 2 ADD ATTRIBUTES/PROPERTIES
newH1.textContent = "I like pizza!";
newH1.id = "myH1";
newH1.style.color…
🌟 Week 4 Day 7 Challenges 🌟
Hello my dear campers 🙌,
You’ve done amazing learning DOM events, onclick, createElement, and appendChild.
Now it’s time to practice with fun challenges that will push your creativity.
Pick any 3 challenges from the list below 👇
1. Click Counters for Like & Dislike Buttons 👍👎
What to do:
➤Create two buttons: "Like" and "Dislike".
➤Each button should count how many times it’s clicked and display the number.
💡Hint:
➥Use let likeCount = 0 and let dislikeCount = 0.
➥Update the text using textContent when a button is clicked.
2. Dynamic Color Changer 🎨
What to do:
➤Make a button that changes the background color of the page every time it’s clicked.
💡Hint:
➥Store a list of colors in an array like ["red", "blue", "green"].
➥On click, randomly pick a color and apply it with document.body.style.backgroundColor.
3. Task List Maker 📝
What to do:
➤Let the user type a task in an input box and add it as a list item when clicking “Add”.
💡Hint:
➥Use document.createElement("li") and appendChild to add new tasks into a <ul>.
➥Don’t forget to grab the input value with .value.
4. Image Switcher 🖼️
What to do:
➤Display an image and a button. When the button is clicked, the image changes.
💡Hint:
➥Use an array of image URLs.
➥Swap the src attribute of the <img> when the button is clicked.
5. Emoji Rain 🌸🍕😂
What to do:
➤Have a button that, when clicked, drops a new emoji onto the page.
💡Hint:
➥Use document.createElement("span").
➥Set its textContent to an emoji.
➥Append it to the body each time the button is clicked.
✨ Choose any 3 challenges, try them out, and have fun!
Don’t forget to
💥💥 share your solutions,
💥💥invite your friends,
and as always…
💥💥✌️✌️stay well, stay curious, and stay coding ✌️
Hello my dear campers 🙌,
You’ve done amazing learning DOM events, onclick, createElement, and appendChild.
Now it’s time to practice with fun challenges that will push your creativity.
Pick any 3 challenges from the list below 👇
1. Click Counters for Like & Dislike Buttons 👍👎
What to do:
➤Create two buttons: "Like" and "Dislike".
➤Each button should count how many times it’s clicked and display the number.
💡Hint:
➥Use let likeCount = 0 and let dislikeCount = 0.
➥Update the text using textContent when a button is clicked.
2. Dynamic Color Changer 🎨
What to do:
➤Make a button that changes the background color of the page every time it’s clicked.
💡Hint:
➥Store a list of colors in an array like ["red", "blue", "green"].
➥On click, randomly pick a color and apply it with document.body.style.backgroundColor.
3. Task List Maker 📝
What to do:
➤Let the user type a task in an input box and add it as a list item when clicking “Add”.
💡Hint:
➥Use document.createElement("li") and appendChild to add new tasks into a <ul>.
➥Don’t forget to grab the input value with .value.
4. Image Switcher 🖼️
What to do:
➤Display an image and a button. When the button is clicked, the image changes.
💡Hint:
➥Use an array of image URLs.
➥Swap the src attribute of the <img> when the button is clicked.
5. Emoji Rain 🌸🍕😂
What to do:
➤Have a button that, when clicked, drops a new emoji onto the page.
💡Hint:
➥Use document.createElement("span").
➥Set its textContent to an emoji.
➥Append it to the body each time the button is clicked.
✨ Choose any 3 challenges, try them out, and have fun!
Don’t forget to
💥💥 share your solutions,
💥💥invite your friends,
and as always…
💥💥✌️✌️stay well, stay curious, and stay coding ✌️