Skip to content

(feat) Day 11 Closure Done #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,5 @@ I am an independent educator and open-source enthusiast who creates meaningful p
### Module 2
- **`Day 08: Mastering JavaScript Execution Context Visually`** - [Watch Video](https://youtu.be/ylx5F7hbzVQ) || [Source Code](https://github.com/tapascript/40-days-of-javascript/blob/main/day-08/README.md)
- **`Day 09: Mastering Temporal Dead Zone and Hoisting`** - [Watch Video](https://youtu.be/OqMxh1QdYEg) || [Source Code](https://github.com/tapascript/40-days-of-javascript/blob/main/day-09/README.md)
- **`Day 10: Mastering Scope and Scope Chain`** - [Watch Video](https://youtu.be/14H2TsrjcLo) || [Source Code](https://github.com/tapascript/40-days-of-javascript/blob/main/day-10/README.md)
- **`Day 10: Mastering Scope and Scope Chain`** - [Watch Video](https://youtu.be/14H2TsrjcLo) || [Source Code](https://github.com/tapascript/40-days-of-javascript/blob/main/day-10/README.md)
- **`Day 11: Learn Closures With Real-World Examples`** - [Watch Video](https://youtu.be/lA7CGz3iHyI) || [Source Code](https://github.com/tapascript/40-days-of-javascript/blob/main/day-11/README.md)
34 changes: 34 additions & 0 deletions day-11/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Day 11 - 40 Days of JavaScript

## **🎯 Goal of This Lesson**

- ✅ Day 11
- ✅ What is Closure in JavaScript?
- ✅ Understanding Closure With Lexical Scope
- ✅ Closure Memorizing Outer Values
- ✅ Closure Real World Use Case
- ✅ Function Factory With Closure
- ✅ Closure & Memory Leak
- ✅ Advantages of Closure
- ✅ Closure & Event Handlers

## 🫶 Support
Your support means a lot.

- Please SUBSCRIBE to [tapaScript YouTube Channel](https://youtube.com/tapasadhikary) if not done already. A Big Thank You!
- Liked my work? It takes months of hard work to create quality content and present it to you. You can show your support to me with a STAR(⭐) to this repository.

> Many Thanks to all the `Stargazers` who have supported this project with stars(⭐)

### 🤝 Sponsor My Work
I am an independent educator and open-source enthusiast who creates meaningful projects to teach programming on my YouTube Channel. **You can support my work by [Sponsoring me on GitHub](https://github.com/sponsors/atapas) or [Buy Me a Cofee](https://buymeacoffee.com/tapasadhikary)**.

## Video
Here is the video for you to go through and learn:

[![day-11](./banner.png)](https://youtu.be/lA7CGz3iHyI "Video")


## **👩‍💻 🧑‍💻 Assignment Tasks**

Please find the task assignments in the [Task File](./task.md).
Binary file added day-11/banner.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions day-11/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Closure</title>
<script defer src="./index.js"></script>
</head>
<body>
<h1>Welcome to the <u>Day 11</u> of "40 Days of JavaScript!"</h1>
</body>
</html>
118 changes: 118 additions & 0 deletions day-11/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
console.log("Day 11 - Closure");

// Outher Inner
function outer() {
let x = 10;

return function inner() {
console.log(x);
};
}

const func = outer();
console.log(func());

// Count Closure
function outerCount() {
let count = 0;

return function innerCount() {
count++;
console.log(count);
};
}

const retVal = outerCount();

retVal(); // 1
retVal(); // 2
retVal(); // 3

// Real World Example

function createBankAccount(initialBalance) {
let balance = initialBalance;

return {
deposit: (amount) => {
balance = balance + amount;
console.log("Deposited ", amount, " Current Balance ", balance);
},

withdraw: (amount) => {
if (amount > balance) {
console.warn("Insifficient Fund");
} else {
balance = balance - amount;
console.log("Withdrawn ", amount, " Current Balance ", balance);
}
},

checkBalance: () => console.log("Current Balance", balance),
};
}

const tapaScriptAccount = createBankAccount(100);

console.log(tapaScriptAccount)

console.log(tapaScriptAccount.deposit(300)); // 400

console.log(tapaScriptAccount.withdraw(50)); // 350

console.log(tapaScriptAccount.withdraw(20)); // 330

console.log(tapaScriptAccount.withdraw(50)); // 280

console.log(tapaScriptAccount.withdraw(150)); // 130

console.log(tapaScriptAccount.checkBalance()); // 130


function dealingWithBigData() {
let bigData = new Array(10000000).fill("*")

return function() {
console.log(bigData[3])
}
}

const variable12 = dealingWithBigData();

console.log(variable12())


// Usefulness of Closure

// 1. You can keep the variables private without exposing them.
// 2. You can stop variable pollution.
// 3. You can create a function factory.
// 4. You can keep a variable alive between multiple calls.

function timer() {
let secs = 0;

return function() {
secs++;
console.log("elaspsed seconds ", secs)
}
}

const timerInstance = timer();
timerInstance(); // 1
timerInstance(); // 2
timerInstance(); // 3


// Closure in Event handler

function setupButton() {
let clickCount = 0;

document.getElementById("myButton").addEventListener("click", function() {
clickCount++;
console.log(`Button clicked ${clickCount} times`);
});
}

setupButton();
41 changes: 41 additions & 0 deletions day-11/task.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Tasks
Please complete the following tasks and post them on the tapaScript Discord under "40 Days of JavaScript".

> **DO NOT USE AI to FIND ANSWERS**. If you are stuck, let's discuss it on DISCORD and learn. Also, please note that none of the answers need you to create any UI. Just focus on the logic building and print the output on the browser console.

## 1. What will be the output of the following code and why?
```js
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter();
counter();
```

## 2. What will be the output and why?
```js
function testClosure() {
let x = 10;
return function () {
return x * x;
};
}
console.log(testClosure()());
```

## 3. Create a button dynamically and attach a click event handler using a closure. The handler should count and log how many times the button was clicked.

## 4. Write a function `createMultiplier(multiplier)` that returns another function to multiply numbers.

## 5. What happens if a closure references an object?
- 1) The object is garbage collected immediately
- 2) The object remains in memory as long as the closure exists
- 3) The object is automatically cloned
- 4) None of the Above.

## 6. Write a function factory of counter to increment, decrement, and reset a counter. Use closure to refer the count value across the functuions.