Forwarded from Birhan Nega
Don’t Let Questions Make You Feel Small
If you're new to coding and constantly feel like:
“Why can’t I solve this small bug?”
“Is it normal to forget things I just learned?”
“Do real developers know all this by heart?”
“Am I even growing at all?”
Here’s my advice:
👉 Don't mistake confusion for failure.
Even experienced developers:
- Forget syntax
- Google daily
- Ask teammates for help
Get stuck on “simple” problems
The difference?
They’ve learned to be calm in the unknown—not because they know everything, but because they’ve been there enough times.
So if you’re asking a lot of questions, feeling lost at times, or doubting yourself...
✅ That’s not a sign you’re failing.
🔥 That’s a sign you’re learning.
📈 That’s how growth feels before it shows results.
-Stick with it.
-Code messy.
-Break things.
-Google hard.
Ask again.
Finish one more day.
That’s how you build a future-proof career. keep showing up
If you're new to coding and constantly feel like:
“Why can’t I solve this small bug?”
“Is it normal to forget things I just learned?”
“Do real developers know all this by heart?”
“Am I even growing at all?”
Here’s my advice:
👉 Don't mistake confusion for failure.
Even experienced developers:
- Forget syntax
- Google daily
- Ask teammates for help
Get stuck on “simple” problems
The difference?
They’ve learned to be calm in the unknown—not because they know everything, but because they’ve been there enough times.
So if you’re asking a lot of questions, feeling lost at times, or doubting yourself...
✅ That’s not a sign you’re failing.
🔥 That’s a sign you’re learning.
📈 That’s how growth feels before it shows results.
-Stick with it.
-Code messy.
-Break things.
-Google hard.
Ask again.
Finish one more day.
That’s how you build a future-proof career. keep showing up
Extra Challenges: Real-World Flavor
👋 Selam Coder Family!
Week 3 is coming to a close, and wow — you’ve already learned variables, loops, conditions, arrays, functions, and more! That’s not beginner stuff anymore — it’s foundational JavaScript! 💪
But guess what?
Coding is like a muscle 💪 — you build it by using it.
That’s why challenges matter. They connect theory to practice, and give you a taste of real-life problem solving.
So today, let’s dive into 5 practical and slightly spicy challenges. We’re slowly introducing you to the harsh but exciting world of coding. 🔥
✅ Choose 4 challenges to work on today (but feel free to try the remaining one if you can!)
1️⃣ 🕵️ Word Blocker
🧠 What to do:
Ask the user to enter a sentence.
Check if it contains any bad words (e.g. "bad", "ugly", etc).
If yes, replace them with "***".
💡 Hints:
Use .includes() to check if a word is in the sentence.
Use .replace() to block the bad word.
You can use .toLowerCase() to make checking easier.
2️⃣ 🎁 Lucky Draw Picker
🧠 What to do:
Let the user enter names of participants (as an array).
Then randomly pick a winner and print it.
💡 Hints:
Use .push() to collect names using prompt inside a loop.
Use Math.random() and Math.floor() to pick a random index.
3️⃣ 🔄 Name Shuffler
🧠 What to do:
Ask the user to enter their full name.
Reverse the letters of first and last name separately.
Then print it out like a fun secret identity.
💡 Hints:
Use .split(" ") to separate first and last names.
Use .split(""), .reverse(), .join("") for reversing.
4️⃣ 🧠 Memory Word Game
🧠 What to do:
Ask the user to enter 8 words (stored in an array).
Then ask: "What was the 3rd word?"
Check if they remember correctly.
💡 Hints:
Use a loop to collect words into an array.
Use array index to compare the original 3rd word with the answer.
5️⃣ ⏰ Simple Alarm Clock (Simulation)
🧠 What to do:
Ask the user for a wake-up hour (e.g. 7).
Use a loop to count from 1 to that number.
At the final hour, print “⏰ Wake up!”
💡 Extra twist:
Add a for loop and an if to simulate "snoozing" if the user says “not now”. 😉
💡 Hints:
Use for to count hours.
You can add prompt() inside the loop to ask "wake up now?"
🤸 Bonus Tip:
➤➤Try combining the techniques you've learned:
➤➤Use functions to organize your code.
➤➤Use arrays for storing user input.
Use loops, if, prompt, return, etc.
💬 Share your solutions in the group, help your friends, and invite others to join the adventure.
We’re building something amazing together — even if we’re just 53 for now 😄
Stay curious, share the love, invite others, and stay well ✌️
#fullstacksummercamp #Week3 #Challenges #JSBootcamp #PracticeToGrow
👋 Selam Coder Family!
Week 3 is coming to a close, and wow — you’ve already learned variables, loops, conditions, arrays, functions, and more! That’s not beginner stuff anymore — it’s foundational JavaScript! 💪
But guess what?
Coding is like a muscle 💪 — you build it by using it.
That’s why challenges matter. They connect theory to practice, and give you a taste of real-life problem solving.
So today, let’s dive into 5 practical and slightly spicy challenges. We’re slowly introducing you to the harsh but exciting world of coding. 🔥
✅ Choose 4 challenges to work on today (but feel free to try the remaining one if you can!)
1️⃣ 🕵️ Word Blocker
🧠 What to do:
Ask the user to enter a sentence.
Check if it contains any bad words (e.g. "bad", "ugly", etc).
If yes, replace them with "***".
💡 Hints:
Use .includes() to check if a word is in the sentence.
Use .replace() to block the bad word.
You can use .toLowerCase() to make checking easier.
2️⃣ 🎁 Lucky Draw Picker
🧠 What to do:
Let the user enter names of participants (as an array).
Then randomly pick a winner and print it.
💡 Hints:
Use .push() to collect names using prompt inside a loop.
Use Math.random() and Math.floor() to pick a random index.
3️⃣ 🔄 Name Shuffler
🧠 What to do:
Ask the user to enter their full name.
Reverse the letters of first and last name separately.
Then print it out like a fun secret identity.
💡 Hints:
Use .split(" ") to separate first and last names.
Use .split(""), .reverse(), .join("") for reversing.
4️⃣ 🧠 Memory Word Game
🧠 What to do:
Ask the user to enter 8 words (stored in an array).
Then ask: "What was the 3rd word?"
Check if they remember correctly.
💡 Hints:
Use a loop to collect words into an array.
Use array index to compare the original 3rd word with the answer.
5️⃣ ⏰ Simple Alarm Clock (Simulation)
🧠 What to do:
Ask the user for a wake-up hour (e.g. 7).
Use a loop to count from 1 to that number.
At the final hour, print “⏰ Wake up!”
💡 Extra twist:
Add a for loop and an if to simulate "snoozing" if the user says “not now”. 😉
💡 Hints:
Use for to count hours.
You can add prompt() inside the loop to ask "wake up now?"
🤸 Bonus Tip:
➤➤Try combining the techniques you've learned:
➤➤Use functions to organize your code.
➤➤Use arrays for storing user input.
Use loops, if, prompt, return, etc.
💬 Share your solutions in the group, help your friends, and invite others to join the adventure.
We’re building something amazing together — even if we’re just 53 for now 😄
Stay curious, share the love, invite others, and stay well ✌️
#fullstacksummercamp #Week3 #Challenges #JSBootcamp #PracticeToGrow
Week 4 Day 1 Js Lesson:
Hey, campers👋
I hope your fingers are feeling strong from all that typing and your brains are warmed up because today we’re officially stepping into Advanced JavaScript territory.
You’ve already met functions before, like old friends — but today, we’re going to dig deeper, learn their secrets, and make them work harder for us.
We’ll cover:
✅Function Declarations vs. Function ✅Expressions
✅Arrow Functions in Depth
✅Default Parameters
✅Rest & Spread Parameters
1️⃣ Function Declarations vs. Function Expressions
In JavaScript, there’s more than one way to create a function.
Function Declaration
This is the classic way — you just declare it, and JavaScript “hoists” it to the top of its scope, meaning you can call it even before it’s written in your code.
Key points:
➥Hoisted (can be used before they appear in code)
➥Good for situations where order in code doesn’t matter
Function Expression
Here, we store the function inside a variable.
These are NOT hoisted, so you can only use them after they are defined.
If we tried calling sayHi() before its definition — ❌ error.
Why use them?
➥More flexible (can pass them around like normal variables)
➥Useful in callbacks and dynamic code
2️⃣ Arrow Functions — in Depth
We’ve met them before, but let’s explore their deeper behavior.
Differences:
➥Shorter Syntax — Good for quick, one-line functions.
➥this Behavior — Arrow functions don’t have their own this.
Instead, they use the this from the surrounding scope.
Example:
Best use for arrow functions:
➥Small callbacks
➥When you want to keep this from the surrounding scope
3️⃣ Default Parameters
Sometimes, you want your function to have a “backup value” if no argument is given.
Why useful?
➥Avoids undefined when arguments are missing
➥Makes functions safer and easier to use
4️⃣ Rest & Spread Parameters
Rest Parameters (...)
When you don’t know how many arguments will be passed, rest parameters collect them into an array.
Spread Operator (...)
Instead of collecting arguments, spread takes an array and spreads its values into separate arguments.
Uses of spread:
➥Copy arrays:
➥Merge arrays:
💡 Summary of Today’s Power-Ups:
✅Declarations vs. Expressions — know when to use each
✅Arrow functions — short & keep this
✅Default parameters — safer function calls
✅Rest & spread — handle many values with elegance
Hey, campers👋
I hope your fingers are feeling strong from all that typing and your brains are warmed up because today we’re officially stepping into Advanced JavaScript territory.
You’ve already met functions before, like old friends — but today, we’re going to dig deeper, learn their secrets, and make them work harder for us.
We’ll cover:
✅Function Declarations vs. Function ✅Expressions
✅Arrow Functions in Depth
✅Default Parameters
✅Rest & Spread Parameters
1️⃣ Function Declarations vs. Function Expressions
In JavaScript, there’s more than one way to create a function.
Function Declaration
This is the classic way — you just declare it, and JavaScript “hoists” it to the top of its scope, meaning you can call it even before it’s written in your code.
// Function Declaration
function sayHello() {
console.log("Hello, campers!"); }
sayHello(); // ✅ Works even if we call it before the function is defined Key points:
➥Hoisted (can be used before they appear in code)
➥Good for situations where order in code doesn’t matter
Function Expression
Here, we store the function inside a variable.
These are NOT hoisted, so you can only use them after they are defined.
// Function Expression
const sayHi = function() {
console.log("Hi, campers!"); };
sayHi(); // ✅ Works here If we tried calling sayHi() before its definition — ❌ error.
Why use them?
➥More flexible (can pass them around like normal variables)
➥Useful in callbacks and dynamic code
2️⃣ Arrow Functions — in Depth
We’ve met them before, but let’s explore their deeper behavior.
// Normal function
const add = function(a, b) {
return a + b; };
// Arrow function
const addArrow = (a, b) => a + b;
Differences:
➥Shorter Syntax — Good for quick, one-line functions.
➥this Behavior — Arrow functions don’t have their own this.
Instead, they use the this from the surrounding scope.
Example:
const person = { name: "Meresa", normalFunc: function() {
console.log("Normal:", this.name); }, arrowFunc: () => {
console.log("Arrow:", this.name); } };
person.normalFunc();
// Normal: Meresa person.arrowFunc();
// Arrow: undefined (because arrow uses global this) Best use for arrow functions:
➥Small callbacks
➥When you want to keep this from the surrounding scope
3️⃣ Default Parameters
Sometimes, you want your function to have a “backup value” if no argument is given.
function greet(name = "Camper") {
console.log(Hello, ${name}!); }
greet("Abebe"); // Hello, Abebe!
greet(); // Hello, Camper!
Why useful?
➥Avoids undefined when arguments are missing
➥Makes functions safer and easier to use
4️⃣ Rest & Spread Parameters
Rest Parameters (...)
When you don’t know how many arguments will be passed, rest parameters collect them into an array.
function sumAll(...numbers) {
let sum = 0;
for (let num of numbers) {
sum += num; }
console.log(sum); }
sumAll(1, 2, 3); // 6
sumAll(5, 10, 15, 20); // 50
Spread Operator (...)
Instead of collecting arguments, spread takes an array and spreads its values into separate arguments.
const nums = [1, 2, 3];
console.log(Math.max(...nums)); // 3 Uses of spread:
➥Copy arrays:
const arr1 = [1, 2, 3];
const arr2 = [...arr1]; ➥Merge arrays:
const arr3 = [4, 5];
const merged = [...arr1, ...arr3]; // [1,2,3,4,5] 💡 Summary of Today’s Power-Ups:
✅Declarations vs. Expressions — know when to use each
✅Arrow functions — short & keep this
✅Default parameters — safer function calls
✅Rest & spread — handle many values with elegance
❤1
Assignment:
➤spread operator
https://youtu.be/RuDdltsfaVc?si=C52S5F7eQuKYGnRZ
➤rest parameter
https://youtu.be/ahwR1D_GAfc?si=HQGuXPDC0H3KJldP
➤spread operator
https://youtu.be/RuDdltsfaVc?si=C52S5F7eQuKYGnRZ
➤rest parameter
https://youtu.be/ahwR1D_GAfc?si=HQGuXPDC0H3KJldP
YouTube
JavaScript SPREAD OPERATOR in 4 minutes! 📖
// spread operator = ... allows an iterable such as an
// array or string to be expanded
// in to separate elements
// (unpacks the elements)
// -------…
// array or string to be expanded
// in to separate elements
// (unpacks the elements)
// -------…
💥💥Week4 day 1 Challenges:
🚀 Challenge 1: Super Combiner
Write a function that can take any number of arrays (not just two!)
Combine them into one single array
The result should have all the items together
💡 Hints
Use rest parameters to grab all the arrays your function receives.
Then, use spread syntax to unpack them into one big array.
Test with fruit names, numbers, or even names of your classmates.
📝 Challenge 2: Sentence Maker
You have a box of words — maybe they’re proverbs from your grandmother or lyrics from your favorite Ethiopian song. Your job: turn them into a beautiful sentence.
That’s your challenge:
Write a function that takes an array of words
Return a string where the words are joined together with spaces
Bonus: allow extra words to be added separately (use rest parameters)
💡 Hints
First, focus on joining the array words together.
Then, think: “What if I also had extra words I wanted to add?”
🎯 Your mission today:
➥Build both functions with your own creativity.
➥Test them with at least three different examples each.
➥Share your funniest or most creative results in the group.
➥Invite a friend to join our camp and most importantly
🔥 Keep the code flowing, keep the smiles glowing! ✌️
🚀 Challenge 1: Super Combiner
Write a function that can take any number of arrays (not just two!)
Combine them into one single array
The result should have all the items together
💡 Hints
Use rest parameters to grab all the arrays your function receives.
Then, use spread syntax to unpack them into one big array.
Test with fruit names, numbers, or even names of your classmates.
📝 Challenge 2: Sentence Maker
You have a box of words — maybe they’re proverbs from your grandmother or lyrics from your favorite Ethiopian song. Your job: turn them into a beautiful sentence.
That’s your challenge:
Write a function that takes an array of words
Return a string where the words are joined together with spaces
Bonus: allow extra words to be added separately (use rest parameters)
💡 Hints
First, focus on joining the array words together.
Then, think: “What if I also had extra words I wanted to add?”
🎯 Your mission today:
➥Build both functions with your own creativity.
➥Test them with at least three different examples each.
➥Share your funniest or most creative results in the group.
➥Invite a friend to join our camp and most importantly
🔥 Keep the code flowing, keep the smiles glowing! ✌️
Week 4 Day 2 JavaScript Lesson:
👋 Selam campers!
Lovely to see you back — hope your brains are rested and your fingers ready. Today we’re diving into two of the most important, beautiful, and practically useful ideas in JavaScript:
✅Higher‑order functions (functions that work with other functions)
✅Closures & lexical scope (how functions remember things)
These two topics are what make JavaScript so flexible and expressive.
🔹 PART 1 — Higher‑Order Functions (HOFs)
What is a higher‑order function?
A higher‑order function is simply a function that takes one or more functions as arguments, and/or returns a function. In other words — functions that treat other functions like data.
Think of it like cooking: a HOF is the recipe that accepts other little recipes (sauces) as ingredients, or spits out a new recipe you can use later.
Why HOFs matter
➤They let you reuse behavior (not just data).
➤They let you abstract patterns (e.g., “do this to every item”).
➤They make code composable, readable, and concise.
Everyday HOFs you already use
↪️map,
↪️filter,
↪️reduce,
↪️ forEach — these are HOFs built into arrays.
Example (map/filter/reduce quick look):
Build-your-own HOF — a simple one
Suppose we want a function that applies any operation to every number:
applyToEach is a HOF because it takes a function (fn) and calls it.
HOF returning a function (function factories)
A HOF can return a function. This is useful for configurable behavior.
Example: a multiplier factory:
Here makeMultiplier returns different functions depending on the factor. Very handy!
Composition example (combine small functions)
We can make new functions by composing smaller functions.
Callbacks (synchronous and asynchronous)
A callback is simply a function passed to another function to be called later.
Synchronous callback:
Asynchronous callback example (you’ll meet async later — this just demonstrates HOF usage over time):
🔹 PART 2 — Lexical Scope & Closures
✅What is lexical scope?
Lexical scope means a function’s available variables are determined by where it was written in the source code, not where it is called.
Example:
The inner function sees food because food existed in the environment where inner was defined.
✅What is a closure?
A closure is when a function remembers the variables from its defining scope, even after that outer function has finished executing.
👋 Selam campers!
Lovely to see you back — hope your brains are rested and your fingers ready. Today we’re diving into two of the most important, beautiful, and practically useful ideas in JavaScript:
✅Higher‑order functions (functions that work with other functions)
✅Closures & lexical scope (how functions remember things)
These two topics are what make JavaScript so flexible and expressive.
🔹 PART 1 — Higher‑Order Functions (HOFs)
What is a higher‑order function?
A higher‑order function is simply a function that takes one or more functions as arguments, and/or returns a function. In other words — functions that treat other functions like data.
Think of it like cooking: a HOF is the recipe that accepts other little recipes (sauces) as ingredients, or spits out a new recipe you can use later.
Why HOFs matter
➤They let you reuse behavior (not just data).
➤They let you abstract patterns (e.g., “do this to every item”).
➤They make code composable, readable, and concise.
Everyday HOFs you already use
↪️map,
↪️filter,
↪️reduce,
↪️ forEach — these are HOFs built into arrays.
Example (map/filter/reduce quick look):
const nums = [1, 2, 3, 4, 5];
const doubled = nums.map(n => n * 2); // [2,4,6,8,10]
const evens = nums.filter(n => n % 2 === 0); // [2,4]
const sum = nums.reduce((acc, n) => acc + n, 0); // 15 Build-your-own HOF — a simple one
Suppose we want a function that applies any operation to every number:
function applyToEach(arr, fn) {
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push(fn(arr[i])); // call the function passed in }
return result; }
const nums = [1, 4, 9];
const roots = applyToEach(nums, Math.sqrt); // [1,2,3] applyToEach is a HOF because it takes a function (fn) and calls it.
HOF returning a function (function factories)
A HOF can return a function. This is useful for configurable behavior.
Example: a multiplier factory:
function makeMultiplier(factor) {
return function(n) { return n * factor; }; }
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15 Here makeMultiplier returns different functions depending on the factor. Very handy!
Composition example (combine small functions)
We can make new functions by composing smaller functions.
const addOne = n => n + 1;
const square = n => n * n;
function compose(f, g) {
return function(x) {
return f(g(x)); }; }
const squareThenAddOne = compose(addOne, square);
console.log(squareThenAddOne(3)); //addOne(square(3)) = 10 Callbacks (synchronous and asynchronous)
A callback is simply a function passed to another function to be called later.
Synchronous callback:
function greetUser(name, printer) {
const message =Selam ${name}!;
printer(message); // call the function passed in }
greetUser("Liya", console.log);
Asynchronous callback example (you’ll meet async later — this just demonstrates HOF usage over time):
setTimeout(() => console.log("Wake up!"), 1000); // callback fired later 🔹 PART 2 — Lexical Scope & Closures
✅What is lexical scope?
Lexical scope means a function’s available variables are determined by where it was written in the source code, not where it is called.
Example:
function outer() {
let food = "injera"; // outer scope variable
function inner() {
console.log(food); // inner can see 'food' because of lexical scope }
inner(); }
outer(); // prints "injera" The inner function sees food because food existed in the environment where inner was defined.
✅What is a closure?
A closure is when a function remembers the variables from its defining scope, even after that outer function has finished executing.
Classic counter example:
Even though createCounter() has finished running, the returned function still remembers count. That remembered state is the closure.
Why closures are useful
↪️Private state: emulate private variables (data hidden from the outside).
↪️Factories: create configured functions (like makeMultiplier).
↪️Event handlers that remember context.
↪️Callbacks that retain data over time.
Private data example (bank account)
Memory & closures — a word of caution
Closures keep references to their outer variables, so those variables stay in memory until no function referencing them exists. That’s usually fine, but be careful:
➤Don’t accidentally keep very large data in a closure if not needed.
➤Remove references when you no longer need them (set to null) if long-lived.
More closure examples
1) Make specialized greeter (function factory)
2) Build a once-only function (run once memo)
3) Using closure with asynchronous callback
✅ Practical advice & patterns
➤Use HOFs to move repeating logic out of loops. Example: abstract “logging” or “validation” into functions you pass around.
➤Use closures when you need private state or a factory that produces configured functions.
➤Prefer let/const over var to avoid subtle closure/loop bugs.
➤Don’t overuse closures for huge data — be mindful of memory.
➤Name functions clearly: makeAdder, filterAdults, sumAll — descriptive names help future-you.
function createCounter() {
let count = 0; // variable in outer scope
return function() { // inner function closes overcount
count += 1;
return count; }; }
const counter = createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 console.log(counter()); // 3
Even though createCounter() has finished running, the returned function still remembers count. That remembered state is the closure.
Why closures are useful
↪️Private state: emulate private variables (data hidden from the outside).
↪️Factories: create configured functions (like makeMultiplier).
↪️Event handlers that remember context.
↪️Callbacks that retain data over time.
Private data example (bank account)
function createAccount(initial) {
let balance = initial; // private
return {
deposit(amount) { if (amount > 0)
balance += amount;
return balance; }, withdraw(amount) { if (amount <= balance)
balance -= amount;
return balance; },
getBalance() {
return balance; } }; }
const account = createAccount(1000);
account.deposit(200); // 1200
account.withdraw(100); // 1100
console.log(account.getBalance());
// 1100
// No direct access tobalancefrom outside — closure keeps it private.
Memory & closures — a word of caution
Closures keep references to their outer variables, so those variables stay in memory until no function referencing them exists. That’s usually fine, but be careful:
➤Don’t accidentally keep very large data in a closure if not needed.
➤Remove references when you no longer need them (set to null) if long-lived.
More closure examples
1) Make specialized greeter (function factory)
function makeGreeter(greeting) {
return function(name) {
console.log(${greeting}, ${name}!); }; }
const saySelam = makeGreeter("Selam");
saySelam("Liya"); // Selam, Liya!
2) Build a once-only function (run once memo)
function once(fn) {
let done = false;
return function(...args) {
if (!done) {
done = true;
return fn(...args); } // otherwise do nothing }; }
const init = once(() => console.log("Initialized"));
init(); // prints init(); // nothing
3) Using closure with asynchronous callback
function delayedGreeter(name) {
const message =Hello ${name};
setTimeout(() => {
console.log(message); // closure keepsmessagealive until callback runs }, 1000); }
delayedGreeter("Sami");
✅ Practical advice & patterns
➤Use HOFs to move repeating logic out of loops. Example: abstract “logging” or “validation” into functions you pass around.
➤Use closures when you need private state or a factory that produces configured functions.
➤Prefer let/const over var to avoid subtle closure/loop bugs.
➤Don’t overuse closures for huge data — be mindful of memory.
➤Name functions clearly: makeAdder, filterAdults, sumAll — descriptive names help future-you.
Assignment
➤map
https://youtu.be/xNQH1NbZQ0E?si=bfCFeYqcmcFNo1hL
➤reduce
https://youtu.be/iDWtuWkuj8g?si=Jcry-t1EtJkIDTye
➤filter
https://youtu.be/VvSEKHKFvpQ?si=5W9FGrriVPTwWpX4
➤closure
https://youtu.be/beZfCfiuIkA?si=5weCkXWQ5df3ckCa
➤map
https://youtu.be/xNQH1NbZQ0E?si=bfCFeYqcmcFNo1hL
➤reduce
https://youtu.be/iDWtuWkuj8g?si=Jcry-t1EtJkIDTye
➤filter
https://youtu.be/VvSEKHKFvpQ?si=5W9FGrriVPTwWpX4
➤closure
https://youtu.be/beZfCfiuIkA?si=5weCkXWQ5df3ckCa
YouTube
JavaScript map() method in 7 minutes! 🗺️
00:00:00 introduciton
00:00:16 example 1
00:02:13 example 2
00:03:58 example 3
// .map() = accepts a callback and applies that function
// to each element of an array, then return a new array
// ------------ EXAMPLE 1 ------------
const…
00:00:16 example 1
00:02:13 example 2
00:03:58 example 3
// .map() = accepts a callback and applies that function
// to each element of an array, then return a new array
// ------------ EXAMPLE 1 ------------
const…
💥💥Week 4 Day 2 challenge
👋 Hey
We’ve got some brain workouts lined up for you, but remember — these aren’t just any exercises… they’re real-world inspired coding adventures 💻✨
Here are 5 mini-quests — pick ANY 3 you like:
🏆 1. Student Score Analyzer
Take an array of student scores and:
Increase every score by 5 (using map).
Keep only students who scored 50+ (using filter).
Find the average score (using reduce).
💡 Hint: Each step can be chained or done separately — your call!
✏️ 2. Word Counter
Ask the user for a sentence.
Count how many times each word appears — but store your counter in a closure so no one else can mess with it!
💡 Hint: .split(" ") is your friend, and your closure will keep the count safe.
🔢 3. Custom Multiplier
Create makeMultiplier(factor) that returns a function which multiplies any number by your factor.
Example:
💡 Hint: That factor lives inside your closure — safe and sound.
📒 4. Activity Logger
Make a closure that keeps a private list of all activities you log (like “Read”, “Code”, “Run”).
Every time you call it, it adds the activity and shows how many you’ve logged so far.
💡 Hint: The activity list should live inside your function and never be exposed directly.
⚖️ 5. Even-Odd Divider
Given an array of numbers, separate them into even and odd arrays using filter().
Print both arrays at the end.
💡 Hint: One filter call for evens, another for odds — short and clean!
🔥 Your Mission: Pick ANY 3 challenges. Tackle them with creativity.
Once done,
▶️share your solutions so we can all learn from each other,
▶️invite a friend to join the fun,
▶️and as always — stay curious, stay coding, and stay well ✌️
👋 Hey
We’ve got some brain workouts lined up for you, but remember — these aren’t just any exercises… they’re real-world inspired coding adventures 💻✨
Here are 5 mini-quests — pick ANY 3 you like:
🏆 1. Student Score Analyzer
Take an array of student scores and:
Increase every score by 5 (using map).
Keep only students who scored 50+ (using filter).
Find the average score (using reduce).
💡 Hint: Each step can be chained or done separately — your call!
✏️ 2. Word Counter
Ask the user for a sentence.
Count how many times each word appears — but store your counter in a closure so no one else can mess with it!
💡 Hint: .split(" ") is your friend, and your closure will keep the count safe.
🔢 3. Custom Multiplier
Create makeMultiplier(factor) that returns a function which multiplies any number by your factor.
Example:
let double = makeMultiplier(2); console.log(double(5)); // 10 💡 Hint: That factor lives inside your closure — safe and sound.
📒 4. Activity Logger
Make a closure that keeps a private list of all activities you log (like “Read”, “Code”, “Run”).
Every time you call it, it adds the activity and shows how many you’ve logged so far.
💡 Hint: The activity list should live inside your function and never be exposed directly.
⚖️ 5. Even-Odd Divider
Given an array of numbers, separate them into even and odd arrays using filter().
Print both arrays at the end.
💡 Hint: One filter call for evens, another for odds — short and clean!
🔥 Your Mission: Pick ANY 3 challenges. Tackle them with creativity.
Once done,
▶️share your solutions so we can all learn from each other,
▶️invite a friend to join the fun,
▶️and as always — stay curious, stay coding, and stay well ✌️
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,
…