Thursday, July 3, 2025

Javascript Module 24



 Javascript Module 24

If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 


https://onlinecourses2024for.blogspot.com/p/contact-us.html/

Javascript Module 24

  Module 24 : Closures in JavaScript 

๐Ÿง   X: Closures in JavaScript


๐Ÿ” What is a Closure?











A closure is a function that remembers its lexical scope, even when the function is executed outside that scope.

In simple terms:

A closure gives you access to an outer function’s scope from an inner function.

Closures are created every time a function is created.


๐Ÿ“š Core Concepts

Lexical Environment:

The place where variables and functions are physically written in the code.

Scope Chain:

A chain of variable environments — local, function, and global.

Closure:

When a function retains access to its parent scope, even after the parent function has finished execution.


✅ Syntax and Basic Example

javascript

code

function outerFunction() { let outerVariable = "I'm from outer scope!"; function innerFunction() { console.log(outerVariable); // innerFunction can access outerVariable } return innerFunction; } const myClosure = outerFunction(); // returns innerFunction myClosure(); // Output: I'm from outer scope!

Explanation:

outerFunction defines a variable outerVariable.

innerFunction is defined inside outerFunction and uses outerVariable.

outerFunction returns innerFunction.

Even after outerFunction completes, innerFunction still has access to outerVariable.

This is the essence of closure.


๐Ÿ› ️ Practical Uses of Closures











Data Encapsulation / Private Variables

javascript

 code

function counter() { let count = 0; return function () { count++; return count; }; } const increment = counter(); console.log(increment()); // 1 console.log(increment()); // 2

Function Factories

javascript

code

function multiplyBy(x) { return function (y) { return x * y; }; } const double = multiplyBy(2); console.log(double(5)); // 10

Memoization (Caching Results)

javascript

code

function memoizedAdd() { let cache = {}; return function (num) { if (num in cache) { return `From Cache: ${cache[num]}`; } else { cache[num] = num + 10; return `Calculated: ${cache[num]}`; } }; } const add = memoizedAdd(); console.log(add(5)); // Calculated: 15 console.log(add(5)); // From Cache: 15


✏️ Exercises With Explanations


Exercise 1: Create a Greeting Closure

Task:

Write a function createGreeter that takes a name and returns a function that greets using that name.




Solution:

javascript

 code

function createGreeter(name) { return function () { console.log(`Hello, ${name}!`); }; } const greetJohn = createGreeter("John"); greetJohn(); // Hello, John!

Explanation:

greetJohn remembers the name passed to createGreeter. This demonstrates closure.


Exercise 2: Encapsulate a Bank Account

Task:

Create a createAccount function that allows deposit and balance checking using closures.

Solution:

javascript

code

function createAccount() { let balance = 0; return { deposit: function (amount) { balance += amount; }, getBalance: function () { return balance; } }; } const account = createAccount(); account.deposit(100); console.log(account.getBalance()); // 100


๐Ÿ”ฌ Timer Counter Using Closures

Objective:

Use closures to create a timer that counts each second and stops at a defined limit.

 Step-by-Step :

Define the timer function

Use closure to maintain state

Use setInterval to update every second

Stop after reaching a limit

javascript

 code

function createTimer(limit) { let count = 0; return function () { const interval = setInterval(() => { count++; console.log(`Timer: ${count}s`); if (count === limit) { clearInterval(interval); console.log("Timer finished."); } }, 1000); }; } const startTimer = createTimer(5); startTimer(); // Will count from 1 to 5

Explanation:

The inner function has access to count and limit, even after createTimer returns.

Closure keeps the variables alive inside setInterval.


๐Ÿ” Research and Deeper Understanding












1. How Closures Manage Memory

Closures retain variables in memory as long as they are accessible. In modern engines like V8, unused closures are garbage-collected, but leaks may occur if not handled properly.

2. Closures in Frameworks

React Hooks (useState) use closures to retain state between renders.

Redux middleware uses closures for state and dispatch access.

Event handlers use closures to capture element-specific data.

3. Closures and Asynchronous JavaScript

Closures are essential in callbacks and promises. For example:

javascript

code

function fetchData(url) { const timestamp = Date.now(); fetch(url).then(response => { console.log(`Fetched at ${timestamp}`); }); }

Here, timestamp is preserved via closure and used when the promise resolves.


๐Ÿง  Summary



Concept

Key Idea

Closure

A function + its lexical environment

Lexical Scope

Scope determined by position in code

Uses

Private variables, memoization, factories

Advanced Usage

Async, React, Event handlers



๐Ÿ“ Homework

Create a closure that tracks a user’s last login time.

Build a shopping cart using closures to add, remove, and total items.

Use a closure to debounce an input field.


Wednesday, July 2, 2025

Javascript Module 23

 


Javascript Module 23

If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 


https://onlinecourses2024for.blogspot.com/p/contact-us.html/

Javascript Module 23

  Module 23 : javascript Higher-Order Functions

๐Ÿง  1. What is a Higher-Order Function?

A Higher-Order Function is a function that takes another function as an argument or returns a function as its result (or both).












javascript

 code

function higherOrder(fn) { return function(x) { return fn(x) + 10; }; }

Here:

higherOrder takes a function fn as an argument and returns another function.

That’s the definition of a Higher-Order Function.


⚙️ 2. Built-In Higher-Order Functions

JavaScript provides several built-in HOFs for arrays:

a. .forEach() – Looping

javascript

 code

let numbers = [1, 2, 3]; numbers.forEach(num => console.log(num * 2)); // Output: 2, 4, 6

Explanation: .forEach() takes a function and applies it to every element.


b. .map() – Transforming Data

javascript

code

let squared = numbers.map(num => num * num); console.log(squared); // Output: [1, 4, 9]

Explanation: .map() returns a new array by applying a function to every element.


c. .filter() – Filtering Data

javascript

code

let even = numbers.filter(num => num % 2 === 0); console.log(even); // Output: [2]

Explanation: .filter() returns elements that satisfy the given condition.


d. .reduce() – Accumulating Data

javascript

code

let sum = numbers.reduce((acc, curr) => acc + curr, 0); console.log(sum); // Output: 6

Explanation: .reduce() returns a single value by accumulating results from left to right.


๐Ÿ—️ 3. Creating Custom Higher-Order Functions

Here’s how you can create your own HOF:

javascript

 code

function repeat(n, action) { for (let i = 0; i < n; i++) { action(i); } } repeat(3, console.log); // Output: 0, 1, 2

Explanation:

repeat is a HOF because it takes action, a function, as a parameter.


 4. HOF for Event Handling









๐Ÿ’ป Objective:

Build a HOF that logs messages differently based on user role.

๐Ÿ”ง Code:

javascript

 code

function createLogger(role) { return function(message) { console.log(`[${role.toUpperCase()}] ${message}`); } } let adminLogger = createLogger('admin'); let userLogger = createLogger('user'); adminLogger('Deleted a post'); // [ADMIN] Deleted a post userLogger('Liked a post'); // [USER] Liked a post

๐Ÿ” Analysis:

createLogger is a HOF — it returns another function based on its input.

This can be used to customize behavior for different user roles.


✏️ 5. Exercises

Exercise 1: Custom Map Function

Write your own version of .map().

javascript

 code

function customMap(arr, transform) { let result = []; for (let i = 0; i < arr.length; i++) { result.push(transform(arr[i])); } return result; } console.log(customMap([1, 2, 3], x => x * 2)); // Output: [2, 4, 6]

Exercise 2: Filter Names

javascript

 code

let names = ["Alice", "Bob", "Charlie", "Anna"]; let filtered = names.filter(name => name.startsWith("A")); console.log(filtered); // Output: ["Alice", "Anna"]


๐Ÿง  6. Conceptual Research

๐Ÿ”น Why Use Higher-Order Functions?


Abstraction: You can abstract logic away into functions.

Modularity: Functions become reusable and composable.

Immutability: Functions like .map() and .filter() do not change the original array.

Readability: Shorter, declarative code.

๐Ÿ”น  Use Cases

ReactJS JSX rendering — .map() used to render lists dynamically.

Node.js API routing — Middleware functions are passed as parameters.

Data transformation pipelines — Chaining .map(), .filter(), and .reduce() for processing.


 7. Assignment: Creating a Data Pipeline

๐ŸŽฏ Goal:

Process a list of students and get average marks of those who passed.

๐Ÿงพ Given:

javascript

 code

let students = [ { name: "Alice", score: 75 }, { name: "Bob", score: 45 }, { name: "Charlie", score: 85 }, { name: "David", score: 60 } ];

๐Ÿงฑ Steps:

Filter those who scored ≥ 60.

Map to extract scores.

Reduce to get the average.

๐Ÿง‘‍๐Ÿ’ป Code:

javascript

 code

let passed = students .filter(student => student.score >= 60) .map(student => student.score); let avg = passed.reduce((a, b) => a + b, 0) / passed.length; console.log("Average of passed students:", avg);

 Output:

shell code

Average of passed students: 73.333...


๐Ÿ“‹ 8. Summary


Feature

Description

What is HOF

Function that takes or returns another function

Built-in Examples

.map(), .filter(), .reduce(), .forEach()

Custom HOF Example

repeat, createLogger

Benefits

Code reuse, clarity, immutability

Focus

Event customization, data pipelines

Research Direction

Data-driven UI, middleware, functional patterns



๐Ÿ“˜ 9. Additional Research Topics


Functional Programming in JavaScript

Pure Functions vs. HOFs

Comparison with Object-Oriented Methods

Performance Analysis of HOFs

Using Lodash’s HOFs for Advanced Pipelines


๐Ÿ“š 10. References


Eloquent JavaScript by Marijn Haverbeke

Mozilla MDN Web Docs: https://developer.mozilla.org

Kyle Simpson, You Don’t Know JS

Functional-Light JavaScript by Kyle Simpson (GitHub open source book)


Tuesday, July 1, 2025

Javascript Module 22

 



Javascript Module 22

If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 


https://onlinecourses2024for.blogspot.com/p/contact-us.html/

Javascript Module 22

 Module 22 : Callback Functions in javascript 

๐Ÿง  What is a Callback Function?

Definition: A callback function is a function passed as an argument to another function and is executed after some operation has been completed.




๐Ÿ”  Analogy

Imagine you're ordering a pizza ๐Ÿ•:

You call the pizza place and order.

Instead of waiting, you give your phone number (callback).

When the pizza is ready, they call you back.

The "call you back" part is the callback function. You continue doing your work and the function is invoked later — just like JavaScript’s asynchronous behavior.


๐Ÿ’ก Basic Syntax and Example

javascript

code

function greetUser(name) { alert('Hello ' + name); } function processUser(callback) { const name = prompt('Please enter your name.'); callback(name); // invoking callback function } processUser(greetUser);

๐Ÿ“Œ Explanation:

greetUser is passed to processUser.

processUser takes a callback and calls it with a parameter.

This is useful for reusability and dynamic behavior.


 1: Write Your Own Callback

















๐ŸŽฏ Goal: Understand basic callback function behavior

javascript

 code

function calculate(num1, num2, callback) { const result = num1 + num2; callback(result); } function showResult(res) { console.log("The result is:", res); } calculate(5, 10, showResult);

✅ Try It:

Change + to *, and observe the output. Try writing a subtraction or division callback too.


๐Ÿ”„ Synchronous vs Asynchronous Callbacks

๐Ÿ”น Synchronous Callback Example

javascript

 code

function syncCallback(name, callback) { console.log("Start"); callback(name); console.log("End"); } syncCallback("Reha", function(name) { console.log("Hello " + name); });

Output:

sql

 code

Start

Hello Reha

End



๐Ÿ”น Asynchronous Callback Example (setTimeout)

javascript

code

function asyncCallback(name, callback) { console.log("Start"); setTimeout(() => { callback(name); }, 2000); console.log("End"); } asyncCallback("Reha", function(name) { console.log("Hello " + name); });

Output:

pgsql

 code

Start

End

Hello (after 2 sec)



๐Ÿง  Concept:

Sync: Runs immediately

Async: Waits for something (like a timer or network request)


๐Ÿ”ง Use Case 1: Event Handling

javascript

 code

document.getElementById("myBtn").addEventListener("click", function() { alert("Button Clicked!"); });

Here, the function inside addEventListener is a callback that is executed when the user clicks.


๐Ÿ”ง Use Case 2: Array Methods











javascript

 code

const numbers = [1, 2, 3]; const doubled = numbers.map(function(num) { return num * 2; }); console.log(doubled); // [2, 4, 6]

๐Ÿ“Œ Explanation:

The map() method takes a callback function that tells it how to transform each item.


๐Ÿ“Š Advanced Example: Simulating an API Call

javascript

code

function fetchData(callback) { setTimeout(() => { const data = { name: "Syeda Rehana", age: 24 }; callback(data); }, 1000); } function processData(userData) { console.log("User fetched:", userData.name, userData.age); } fetchData(processData);

๐Ÿ“Œ  use:

Useful in web development when you fetch user data from APIs.


 2: Build Your Own Asynchronous Callback

Task: Create a fake API to fetch product data using callbacks.

javascript

code

function getProduct(callback) { setTimeout(() => { const product = { id: 1, name: "Laptop", price: 49999 }; callback(product); }, 1500); } function displayProduct(product) { console.log("Product:", product.name, "Price:", product.price); } getProduct(displayProduct);

✅ Modify the callback to apply a discount or show in alert box


๐Ÿ“š Research Insight: Why Callbacks Matter




JavaScript uses non-blocking asynchronous programming to handle things like:

HTTP requests

Event listeners

Timers

File reading (in Node.js)

๐Ÿงต Callback Problem

Nested callbacks can become hard to manage:

javascript

 code

loginUser("Rehana", () => { getProfile(() => { loadDashboard(() => { // very hard to read }); }); });

๐Ÿ› ️ Solution: Use Promises or Async/Await (covered in next module).


✅ Best Practices

Do

Avoid

Name your callback functions

Anonymous nested functions everywhere

Handle errors in callbacks

Assuming success always

Use arrow functions for cleaner syntax

Callback inside callback inside callback

Move toward Promises for complex flows

Sticking to callbacks only for async tasks



๐Ÿง   Questions

What is a callback function?

What's the difference between synchronous and asynchronous callbacks?

What issue does "callback" describe?

Modify a callback to add logging before and after it runs.


๐Ÿ—ฃ️ Presentation Tips








Start with analogy (e.g., pizza order, phone calls)

Live-code a simple callback

Show browser dev tools, console.log to trace flow

Show async delay with setTimeout

Compare it with Promises to build curiosity

Give incremental exercises


 Event-Based Callback System

Task: Create a mini event handler system using callbacks.

javascript

 code

function onEvent(message, callback) { console.log("System Message:", message); callback(); } onEvent("New message received", function() { console.log("Opening message view..."); });

๐Ÿ” Enhance this by adding a time delay, or multiple events.


๐Ÿ”š Summary

A callback is a function passed to another function to be executed later.








JavaScript uses callbacks heavily in async operations and event-driven systems.

Callbacks promote code reuse and modular design.

Be cautious of callback l; use promises or async/await when needed.



Javascript Module 24

  Javascript Module 24 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test A...