# π JavaScript Tutorial - Part 2/10: Control Flow & Functions
#JavaScript #WebDev #Programming #Beginners
Welcome to Part 2 of our JavaScript series! Today we'll master decision-making and functions - the building blocks of programming logic.
---
## πΉ Conditional Statements
Control program flow based on conditions.
### 1. if-else Statement
### 2. Ternary Operator (Shorthand if-else)
### 3. switch-case Statement
---
## πΉ Loops
Execute code repeatedly.
### 1. for Loop
### 2. while Loop
### 3. do-while Loop
### 4. for...of Loop (Arrays)
### 5. for...in Loop (Objects)
---
## πΉ Functions
Reusable blocks of code.
### 1. Function Declaration
### 2. Function Expression
### 3. Arrow Functions (ES6+)
### 4. Default Parameters
### 5. Rest Parameters
---
## πΉ Practical Example: Grade Calculator
---
## πΉ Scope in JavaScript
### 1. Global Scope
### 2. Function Scope (var)
### 3. Block Scope (let/const)
---
## πΉ Error Handling
### 1. try-catch-finally
### 2. Throwing Custom Errors
---
## πΉ Best Practices
1. Use strict equality (
2. Prefer const/let over var
3. Keep functions small/single-purpose
4. Always handle errors
5. Use descriptive names for functions/variables
---
### π What's Next?
In Part 3, we'll cover:
β‘οΈ Arrays & Array Methods
β‘οΈ Objects & JSON
β‘οΈ Destructuring
#LearnJavaScript #CodingBasics #WebDevelopment π
Practice Exercise:
1. Create a function to check if a number is even/odd
2. Write a loop that prints prime numbers up to 20
3. Make a temperature converter function (Celsius βοΈ Fahrenheit)
#JavaScript #WebDev #Programming #Beginners
Welcome to Part 2 of our JavaScript series! Today we'll master decision-making and functions - the building blocks of programming logic.
---
## πΉ Conditional Statements
Control program flow based on conditions.
### 1. if-else Statement
let age = 18;
if (age >= 18) {
console.log("You're an adult");
} else {
console.log("You're a minor");
}
### 2. Ternary Operator (Shorthand if-else)
let message = (age >= 18) ? "Adult" : "Minor";
console.log(message);
### 3. switch-case Statement
let day = 3;
let dayName;
switch(day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
default: dayName = "Unknown";
}
console.log(dayName); // "Wednesday"
---
## πΉ Loops
Execute code repeatedly.
### 1. for Loop
for (let i = 1; i <= 5; i++) {
console.log(`Count: ${i}`);
}
// Output: 1, 2, 3, 4, 5### 2. while Loop
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
### 3. do-while Loop
let x = 1;
do {
console.log(x);
x++;
} while (x <= 5);
### 4. for...of Loop (Arrays)
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
### 5. for...in Loop (Objects)
const person = {name: "Ali", age: 25};
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}---
## πΉ Functions
Reusable blocks of code.
### 1. Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Ali")); // "Hello, Ali!"### 2. Function Expression
const square = function(x) {
return x * x;
};
console.log(square(5)); // 25### 3. Arrow Functions (ES6+)
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
### 4. Default Parameters
function createUser(name, role = "user") {
console.log(`${name} is a ${role}`);
}
createUser("Ali"); // "Ali is a user"### 5. Rest Parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6---
## πΉ Practical Example: Grade Calculator
function calculateGrade(score) {
if (score >= 90) return "A";
else if (score >= 80) return "B";
else if (score >= 70) return "C";
else return "F";
}
const studentScore = 85;
console.log(`Grade: ${calculateGrade(studentScore)}`); // "Grade: B"---
## πΉ Scope in JavaScript
### 1. Global Scope
const globalVar = "I'm global";
function test() {
console.log(globalVar); // Accessible
}
### 2. Function Scope (var)
function test() {
var functionVar = "I'm function-scoped";
}
console.log(functionVar); // Error: Not accessible### 3. Block Scope (let/const)
if (true) {
let blockVar = "I'm block-scoped";
}
console.log(blockVar); // Error: Not accessible---
## πΉ Error Handling
### 1. try-catch-finally
try {
// Risky code
nonExistentFunction();
} catch (error) {
console.log("Error occurred:", error.message);
} finally {
console.log("This always executes");
}### 2. Throwing Custom Errors
function divide(a, b) {
if (b === 0) throw new Error("Cannot divide by zero!");
return a / b;
}---
## πΉ Best Practices
1. Use strict equality (
===) over == 2. Prefer const/let over var
3. Keep functions small/single-purpose
4. Always handle errors
5. Use descriptive names for functions/variables
---
### π What's Next?
In Part 3, we'll cover:
β‘οΈ Arrays & Array Methods
β‘οΈ Objects & JSON
β‘οΈ Destructuring
#LearnJavaScript #CodingBasics #WebDevelopment π
Practice Exercise:
1. Create a function to check if a number is even/odd
2. Write a loop that prints prime numbers up to 20
3. Make a temperature converter function (Celsius βοΈ Fahrenheit)
β€5
# π JavaScript Tutorial - Part 3/10: Arrays, Objects & JSON
#JavaScript #WebDev #Programming #DataStructures
Welcome to Part 3 of our JavaScript series! Today we'll master arrays, objects, and JSON - essential for handling complex data.
---
## πΉ Arrays in JavaScript
Ordered collections that can hold multiple values.
### 1. Creating Arrays
### 2. Accessing Elements
### 3. Common Array Methods
| Method | Description | Example |
|--------|-------------|---------|
|
|
|
|
|
|
---
## πΉ Modern Array Methods (ES6+)
Powerful functional programming tools.
### 1. forEach()
### 2. map()
### 3. filter()
### 4. reduce()
### 5. find() & findIndex()
### 6. some() & every()
---
## πΉ Objects in JavaScript
Collections of key-value pairs (properties).
### 1. Creating Objects
### 2. Accessing Properties
### 3. Modifying Objects
---
## πΉ Object Methods
### 1. Object.keys()
### 2. Object.values()
### 3. Object.entries()
### 4. Object Spread (ES9+)
---
## πΉ JSON (JavaScript Object Notation)
Universal data format for APIs.
### 1. JSON βοΈ JavaScript
### 2. JSON Structure
---
## πΉ Destructuring Assignment
Unpack values from arrays/objects.
### 1. Array Destructuring
### 2. Object Destructuring
### 3. Function Parameter Destructuring
---
#JavaScript #WebDev #Programming #DataStructures
Welcome to Part 3 of our JavaScript series! Today we'll master arrays, objects, and JSON - essential for handling complex data.
---
## πΉ Arrays in JavaScript
Ordered collections that can hold multiple values.
### 1. Creating Arrays
// Array literal (recommended)
const fruits = ['Apple', 'Banana', 'Orange'];
// Array constructor
const numbers = new Array(1, 2, 3);
// Mixed data types
const mixed = [1, 'Hello', true, {name: 'Ali'}];
### 2. Accessing Elements
console.log(fruits[0]); // "Apple" (0-based index)
console.log(fruits.length); // 3
### 3. Common Array Methods
| Method | Description | Example |
|--------|-------------|---------|
|
push() | Add to end | fruits.push('Mango') ||
pop() | Remove from end | fruits.pop() ||
shift() | Remove from start | fruits.shift() ||
unshift() | Add to start | fruits.unshift('Kiwi') ||
slice() | Get sub-array | fruits.slice(1, 3) ||
splice() | Add/remove items | fruits.splice(1, 0, 'Berry') |---
## πΉ Modern Array Methods (ES6+)
Powerful functional programming tools.
### 1. forEach()
fruits.forEach(fruit => console.log(fruit));
### 2. map()
const upperFruits = fruits.map(fruit => fruit.toUpperCase());
### 3. filter()
const longFruits = fruits.filter(fruit => fruit.length > 5);
### 4. reduce()
const sum = [1, 2, 3].reduce((total, num) => total + num, 0);
### 5. find() & findIndex()
const banana = fruits.find(fruit => fruit === 'Banana');
const bananaIndex = fruits.findIndex(fruit => fruit === 'Banana');
### 6. some() & every()
const hasApple = fruits.some(fruit => fruit === 'Apple');
const allLong = fruits.every(fruit => fruit.length > 3);
---
## πΉ Objects in JavaScript
Collections of key-value pairs (properties).
### 1. Creating Objects
// Object literal (recommended)
const person = {
name: 'Ali',
age: 25,
hobbies: ['reading', 'coding'],
address: {
city: 'Dubai',
country: 'UAE'
}
};
### 2. Accessing Properties
// Dot notation
console.log(person.name); // "Ali"
// Bracket notation (useful for dynamic keys)
const key = 'age';
console.log(person[key]); // 25
### 3. Modifying Objects
// Add property
person.job = 'Developer';
// Delete property
delete person.age;
// Check property existence
'name' in person; // true
---
## πΉ Object Methods
### 1. Object.keys()
const keys = Object.keys(person); // ["name", "age", ...]
### 2. Object.values()
const values = Object.values(person);
### 3. Object.entries()
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}### 4. Object Spread (ES9+)
const newPerson = {...person, age: 26};---
## πΉ JSON (JavaScript Object Notation)
Universal data format for APIs.
### 1. JSON βοΈ JavaScript
// Object to JSON string
const jsonStr = JSON.stringify(person);
// JSON string to object
const parsedObj = JSON.parse(jsonStr);
### 2. JSON Structure
{
"name": "Ali",
"age": 25,
"isStudent": false,
"courses": ["Math", "CS"]
}---
## πΉ Destructuring Assignment
Unpack values from arrays/objects.
### 1. Array Destructuring
const [first, second] = fruits;
console.log(first); // "Apple"
### 2. Object Destructuring
const {name, age} = person;
console.log(name); // "Ali"
// With renaming
const {name: personName} = person;### 3. Function Parameter Destructuring
function printUser({name, age}) {
console.log(`${name} is ${age} years old`);
}---
## πΉ Practical Example: Todo List Manager
---
## πΉ Best Practices
1. Use `const` for arrays/objects (the reference is constant)
2. Prefer functional methods (
3. Validate JSON before parsing
4. Use descriptive property names
5. Destructure deeply nested objects carefully
---
### π What's Next?
In Part 4, we'll cover:
β‘οΈ DOM Manipulation
β‘οΈ Event Handling
β‘οΈ Form Validation
#JavaScript #WebDevelopment #Programming π
Practice Exercise:
1. Create an array of products (name, price, inStock)
2. Write functions to:
- Filter out-of-stock products
- Calculate total inventory value
- Sort by price (high-to-low)
3. Convert your array to JSON and back
const todoList = [
{id: 1, task: 'Buy groceries', completed: false},
{id: 2, task: 'Do laundry', completed: true}
];
// Add new task
function addTask(task) {
const newTask = {
id: todoList.length + 1,
task,
completed: false
};
todoList.push(newTask);
}
// Mark task as complete
function completeTask(id) {
const task = todoList.find(item => item.id === id);
if (task) task.completed = true;
}
// Get pending tasks
function getPendingTasks() {
return todoList.filter(task => !task.completed);
}
---
## πΉ Best Practices
1. Use `const` for arrays/objects (the reference is constant)
2. Prefer functional methods (
map, filter) over loops3. Validate JSON before parsing
4. Use descriptive property names
5. Destructure deeply nested objects carefully
---
### π What's Next?
In Part 4, we'll cover:
β‘οΈ DOM Manipulation
β‘οΈ Event Handling
β‘οΈ Form Validation
#JavaScript #WebDevelopment #Programming π
Practice Exercise:
1. Create an array of products (name, price, inStock)
2. Write functions to:
- Filter out-of-stock products
- Calculate total inventory value
- Sort by price (high-to-low)
3. Convert your array to JSON and back
# π JavaScript Tutorial - Part 4/10: DOM Manipulation & Events
#JavaScript #WebDev #FrontEnd #DOM
Welcome to Part 4 of our JavaScript series! Today we'll learn how to make web pages interactive by mastering DOM manipulation and event handling.
---
## πΉ What is the DOM?
The Document Object Model is a tree-like representation of your webpage that JavaScript can interact with.
---
## πΉ Selecting DOM Elements
### 1. Single Element Selectors
### 2. Multiple Element Selectors
---
## πΉ Modifying the DOM
### 1. Changing Content
### 2. Styling Elements
### 3. Creating & Adding Elements
---
## πΉ Event Handling
Responding to user interactions.
### 1. Inline Events (Avoid)
### 2. Recommended Approach
### 3. Common Event Types
| Event | Description |
|-------|-------------|
|
|
|
|
|
|
|
---
## πΉ Event Object & Propagation
### 1. Event Object Properties
### 2. Stopping Propagation
### 3. Event Delegation
---
#JavaScript #WebDev #FrontEnd #DOM
Welcome to Part 4 of our JavaScript series! Today we'll learn how to make web pages interactive by mastering DOM manipulation and event handling.
---
## πΉ What is the DOM?
The Document Object Model is a tree-like representation of your webpage that JavaScript can interact with.
<!-- HTML Structure -->
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1 id="main-title">Hello World</h1>
<ul class="items">
<li>Item 1</li>
<li>Item 2</li>
</ul>
</body>
</html>
graph TD
document --> html
html --> head
html --> body
head --> title
title --> text["My Page"]
body --> h1
h1 --> h1text["Hello World"]
body --> ul
ul --> li1["Item 1"]
ul --> li2["Item 2"]
---
## πΉ Selecting DOM Elements
### 1. Single Element Selectors
// By ID (returns single element)
const title = document.getElementById('main-title');
// By CSS selector (first match)
const item = document.querySelector('.items li');
### 2. Multiple Element Selectors
// By class name (HTMLCollection)
const items = document.getElementsByClassName('item');
// By tag name (HTMLCollection)
const listItems = document.getElementsByTagName('li');
// By CSS selector (NodeList)
const allItems = document.querySelectorAll('.items li');
---
## πΉ Modifying the DOM
### 1. Changing Content
// Text content (better for security)
title.textContent = 'New Title';
// HTML content (use carefully!)
title.innerHTML = '<em>New</em> Title';
// Attribute changes
title.setAttribute('class', 'highlight');
### 2. Styling Elements
// Direct style property access
title.style.color = 'blue';
title.style.fontSize = '2rem';
// Multiple styles at once
title.style.cssText = 'color: blue; font-size: 2rem;';
// Toggle classes
title.classList.add('highlight');
title.classList.remove('highlight');
title.classList.toggle('highlight');
### 3. Creating & Adding Elements
// Create new element
const newItem = document.createElement('li');
newItem.textContent = 'Item 3';
// Append to parent
const list = document.querySelector('ul');
list.appendChild(newItem);
// Insert at specific position
list.insertBefore(newItem, list.children[1]);
// Remove elements
list.removeChild(newItem);
---
## πΉ Event Handling
Responding to user interactions.
### 1. Inline Events (Avoid)
<button onclick="handleClick()">Click Me</button>
### 2. Recommended Approach
const button = document.querySelector('button');
// Add event listener
button.addEventListener('click', function(e) {
console.log('Button clicked!', e.target);
});
// Remove event listener
button.removeEventListener('click', handleClick);### 3. Common Event Types
| Event | Description |
|-------|-------------|
|
click | Mouse click ||
dblclick | Double click ||
mouseenter/mouseleave | Hover effects ||
keydown/keyup | Keyboard input ||
submit | Form submission ||
load | Page/images loaded ||
scroll | Page scrolling |---
## πΉ Event Object & Propagation
### 1. Event Object Properties
element.addEventListener('click', function(event) {
console.log(event.type); // "click"
console.log(event.target); // Clicked element
console.log(event.clientX); // Mouse X position
console.log(event.key); // Key pressed (for keyboard events)
});### 2. Stopping Propagation
// Stop bubbling up
event.stopPropagation();
// Prevent default behavior
event.preventDefault();
### 3. Event Delegation
document.querySelector('ul').addEventListener('click', function(e) {
if (e.target.tagName === 'LI') {
console.log('List item clicked:', e.target.textContent);
}
});---
β€2
## πΉ Practical Example: Interactive Todo List
---
## πΉ Working with Forms
### 1. Accessing Form Data
### 2. Form Validation
---
## πΉ Best Practices
1. Cache DOM queries (store in variables)
2. Use event delegation for dynamic elements
3. Always prevent default on form submissions
4. Separate JS from HTML (avoid inline handlers)
5. Throttle rapid-fire events (resize, scroll)
---
### π What's Next?
In Part 5, we'll cover:
β‘οΈ Asynchronous JavaScript
β‘οΈ Callbacks, Promises, Async/Await
β‘οΈ Fetch API & AJAX
#JavaScript #FrontEnd #WebDevelopment π
Practice Exercise:
1. Create a color picker that changes background color
2. Build a counter with + and - buttons
3. Make a dropdown menu that shows/hides on click
// DOM Elements
const form = document.querySelector('#todo-form');
const input = document.querySelector('#todo-input');
const list = document.querySelector('#todo-list');
// Add new todo
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value.trim() === '') return;
const todoText = input.value;
const li = document.createElement('li');
li.innerHTML = `
${todoText}
<button class="delete-btn">X</button>
`;
list.appendChild(li);
input.value = '';
});
// Delete todo (using delegation)
list.addEventListener('click', function(e) {
if (e.target.classList.contains('delete-btn')) {
e.target.parentElement.remove();
}
});
---
## πΉ Working with Forms
### 1. Accessing Form Data
const form = document.querySelector('form');
form.addEventListener('submit', function(e) {
e.preventDefault();
// Get form values
const username = form.elements['username'].value;
const password = form.elements['password'].value;
console.log({ username, password });
});### 2. Form Validation
function validateForm() {
const email = document.getElementById('email').value;
if (!email.includes('@')) {
alert('Please enter a valid email');
return false;
}
return true;
}---
## πΉ Best Practices
1. Cache DOM queries (store in variables)
2. Use event delegation for dynamic elements
3. Always prevent default on form submissions
4. Separate JS from HTML (avoid inline handlers)
5. Throttle rapid-fire events (resize, scroll)
---
### π What's Next?
In Part 5, we'll cover:
β‘οΈ Asynchronous JavaScript
β‘οΈ Callbacks, Promises, Async/Await
β‘οΈ Fetch API & AJAX
#JavaScript #FrontEnd #WebDevelopment π
Practice Exercise:
1. Create a color picker that changes background color
2. Build a counter with + and - buttons
3. Make a dropdown menu that shows/hides on click
β€2
Forwarded from Machine Learning with Python
ππΈ 500$ FOR THE FIRST 500 WHO JOIN THE CHANNEL! ππΈ
Join our channel today for free! Tomorrow it will cost 500$!
https://t.iss.one/+QHlfCJcO2lRjZWVl
You can join at this link! ππ
https://t.iss.one/+QHlfCJcO2lRjZWVl
Join our channel today for free! Tomorrow it will cost 500$!
https://t.iss.one/+QHlfCJcO2lRjZWVl
You can join at this link! ππ
https://t.iss.one/+QHlfCJcO2lRjZWVl
β€1
Data Analytics
## πΉ Practical Example: Interactive Todo List // DOM Elements const form = document.querySelector('#todo-form'); const input = document.querySelector('#todo-input'); const list = document.querySelector('#todo-list'); // Add new todo form.addEventListener('submit'β¦
# π JavaScript Tutorial - Part 5/10: Asynchronous JavaScript
#JavaScript #Async #Promises #FetchAPI #WebDev
Welcome to Part 5 of our JavaScript series! Today we'll conquer asynchronous programming - the key to handling delays, API calls, and non-blocking operations.
---
## πΉ Synchronous vs Asynchronous
### 1. Synchronous Execution
### 2. Asynchronous Execution
---
## πΉ Callback Functions
Traditional way to handle async operations.
### 1. Basic Callback
### 2. Callback Hell (The Pyramid of Doom)
---
## πΉ Promises (ES6)
Modern solution for async operations.
### 1. Promise States
- Pending: Initial state
- Fulfilled: Operation completed successfully
- Rejected: Operation failed
### 2. Creating Promises
### 3. Using Promises
### 4. Promise Chaining
### 5. Promise Methods
---
## πΉ Async/Await (ES8)
Syntactic sugar for promises.
### 1. Basic Usage
### 2. Parallel Execution
---
## πΉ Fetch API
Modern way to make HTTP requests.
### 1. GET Request
### 2. POST Request
### 3. Error Handling
---
## πΉ Practical Example: Weather App
---
## πΉ AJAX with XMLHttpRequest (Legacy)
Older way to make requests (still good to know).
#JavaScript #Async #Promises #FetchAPI #WebDev
Welcome to Part 5 of our JavaScript series! Today we'll conquer asynchronous programming - the key to handling delays, API calls, and non-blocking operations.
---
## πΉ Synchronous vs Asynchronous
### 1. Synchronous Execution
console.log("Step 1");
console.log("Step 2"); // Waits for Step 1
console.log("Step 3"); // Waits for Step 2### 2. Asynchronous Execution
console.log("Start");
setTimeout(() => {
console.log("Async operation complete");
}, 2000);
console.log("End");
// Output order: Start β End β Async operation complete---
## πΉ Callback Functions
Traditional way to handle async operations.
### 1. Basic Callback
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
fetchData((data) => {
console.log(data); // "Data received" after 1 second
});### 2. Callback Hell (The Pyramid of Doom)
getUser(user => {
getPosts(user.id, posts => {
getComments(posts[0].id, comments => {
console.log(comments); // Nested nightmare!
});
});
});---
## πΉ Promises (ES6)
Modern solution for async operations.
### 1. Promise States
- Pending: Initial state
- Fulfilled: Operation completed successfully
- Rejected: Operation failed
### 2. Creating Promises
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
success ? resolve("Data fetched!") : reject("Error!");
}, 1500);
});### 3. Using Promises
fetchData
.then(data => console.log(data))
.catch(error => console.error(error))
.finally(() => console.log("Done!"));
### 4. Promise Chaining
fetchUser()
.then(user => fetchPosts(user.id))
.then(posts => fetchComments(posts[0].id))
.then(comments => console.log(comments))
.catch(error => console.error(error));
### 5. Promise Methods
Promise.all([promise1, promise2]) // Waits for all
Promise.race([promise1, promise2]) // First to settle
Promise.any([promise1, promise2]) // First to fulfill
---
## πΉ Async/Await (ES8)
Syntactic sugar for promises.
### 1. Basic Usage
async function getData() {
try {
const response = await fetchData();
console.log(response);
} catch (error) {
console.error(error);
}
}### 2. Parallel Execution
async function fetchAll() {
const [users, posts] = await Promise.all([
fetchUsers(),
fetchPosts()
]);
console.log(users, posts);
}---
## πΉ Fetch API
Modern way to make HTTP requests.
### 1. GET Request
async function getUsers() {
const response = await fetch('https://api.example.com/users');
const data = await response.json();
return data;
}### 2. POST Request
async function createUser(user) {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
});
return response.json();
}### 3. Error Handling
async function safeFetch(url) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(response.status);
return await response.json();
} catch (error) {
console.error("Fetch failed:", error);
}
}---
## πΉ Practical Example: Weather App
async function getWeather(city) {
try {
const apiKey = 'YOUR_API_KEY';
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`
);
if (!response.ok) throw new Error('City not found');
const data = await response.json();
return {
temp: Math.round(data.main.temp - 273.15), // Kelvin β Celsius
conditions: data.weather[0].main
};
} catch (error) {
console.error("Weather fetch error:", error);
return null;
}
}
// Usage
const weather = await getWeather("London");
if (weather) {
console.log(`Temperature: ${weather.temp}Β°C`);
console.log(`Conditions: ${weather.conditions}`);
}---
## πΉ AJAX with XMLHttpRequest (Legacy)
Older way to make requests (still good to know).
Data Analytics
## πΉ Practical Example: Interactive Todo List // DOM Elements const form = document.querySelector('#todo-form'); const input = document.querySelector('#todo-input'); const list = document.querySelector('#todo-list'); // Add new todo form.addEventListener('submit'β¦
function oldFetch(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = () => {
if (xhr.status === 200) {
callback(JSON.parse(xhr.response));
} else {
callback(null, xhr.status);
}
};
xhr.send();
}---
## πΉ Best Practices
1. Always handle errors in promises/async functions
2. Use async/await for better readability
3. Cancel requests when no longer needed (AbortController)
4. Throttle rapid API calls (debounce input handlers)
5. Cache responses when appropriate
---
### π What's Next?
In Part 6, we'll cover:
β‘οΈ JavaScript Modules
β‘οΈ ES6+ Features
β‘οΈ Tooling (Babel, Webpack, npm)
#JavaScript #AsyncProgramming #WebDevelopment π
Practice Exercise:
1. Fetch GitHub user data (https://api.github.com/users/username)
2. Create a function that fetches multiple PokΓ©mon in parallel
3. Build a retry mechanism for failed requests (max 3 attempts)
Data Analytics
function oldFetch(url, callback) { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = () => { if (xhr.status === 200) { callback(JSON.parse(xhr.response)); } else { callback(null, xhr.status); } }; xhr.send();β¦
# π JavaScript Tutorial - Part 6/10: Modules & Modern JavaScript
#JavaScript #ES6 #Modules #Webpack #ModernJS
Welcome to Part 6 of our JavaScript series! Today we'll explore code organization with modules and modern JavaScript features that revolutionized frontend development.
---
## πΉ JavaScript Modules
### 1. Module Systems Comparison
| System | Syntax | Environment | Features |
|--------------|-----------------|--------------|----------|
| ES Modules |
| CommonJS |
| AMD |
### 2. ES Modules (ES6)
#### Exporting:
#### Importing:
### 3. HTML Integration
---
## πΉ Modern JavaScript Features
### 1. Block-Scoped Declarations (ES6)
### 2. Template Literals (ES6)
### 3. Arrow Functions (ES6)
### 4. Destructuring (ES6)
### 5. Spread/Rest Operator (ES6)
### 6. Optional Chaining (ES2020)
### 7. Nullish Coalescing (ES2020)
---
## πΉ JavaScript Tooling
### 1. Package Management with npm/yarn
### 2. Module Bundlers
#### Webpack Configuration (
### 3. Babel (JavaScript Compiler)
####
### 4. ESLint (Code Linter)
####
---
## πΉ Practical Example: Modular App Structure
Example Component (`components/header.js`):
Main Entry Point (`index.js`):
---
#JavaScript #ES6 #Modules #Webpack #ModernJS
Welcome to Part 6 of our JavaScript series! Today we'll explore code organization with modules and modern JavaScript features that revolutionized frontend development.
---
## πΉ JavaScript Modules
### 1. Module Systems Comparison
| System | Syntax | Environment | Features |
|--------------|-----------------|--------------|----------|
| ES Modules |
import/export | Modern browsers, Node.js | Native standard || CommonJS |
require/module.exports | Node.js | Legacy Node || AMD |
define/require | Browser | Async loading |### 2. ES Modules (ES6)
#### Exporting:
// Named exports (multiple per file)
export const API_URL = 'https://api.example.com';
export function fetchData() { /* ... */ }
// Default export (one per file)
export default class User { /* ... */ }
#### Importing:
// Named imports
import { API_URL, fetchData } from './utils.js';
// Default import
import User from './models/User.js';
// Mixed imports
import User, { API_URL } from './config.js';
// Import everything
import * as utils from './utils.js';
### 3. HTML Integration
<script type="module">
import { initApp } from './app.js';
initApp();
</script>
---
## πΉ Modern JavaScript Features
### 1. Block-Scoped Declarations (ES6)
let x = 10; // Block-scoped variable
const PI = 3.14; // Block-scoped constant
### 2. Template Literals (ES6)
const name = 'Ali';
console.log(`Hello ${name}! Today is ${new Date().toLocaleDateString()}`);
### 3. Arrow Functions (ES6)
const add = (a, b) => a + b;
[1, 2, 3].map(n => n * 2);
### 4. Destructuring (ES6)
// Array destructuring
const [first, second] = [1, 2];
// Object destructuring
const { name, age } = user;
### 5. Spread/Rest Operator (ES6)
// Spread
const nums = [1, 2, 3];
const newNums = [...nums, 4, 5];
// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
### 6. Optional Chaining (ES2020)
const street = user?.address?.street; // No error if null
### 7. Nullish Coalescing (ES2020)
const limit = config.maxItems ?? 10; // Only if null/undefined
---
## πΉ JavaScript Tooling
### 1. Package Management with npm/yarn
npm init -y # Initialize project
npm install lodash # Install package
npm install --save-dev webpack # Dev dependency
### 2. Module Bundlers
#### Webpack Configuration (
webpack.config.js):module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};### 3. Babel (JavaScript Compiler)
####
.babelrc Configuration:{
"presets": ["@babel/preset-env"],
"plugins": ["@babel/plugin-transform-runtime"]
}### 4. ESLint (Code Linter)
####
.eslintrc.json Example:{
"extends": "eslint:recommended",
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "single"]
}
}---
## πΉ Practical Example: Modular App Structure
project/
βββ src/
β βββ index.js # Entry point
β βββ utils/ # Helper modules
β β βββ api.js # API functions
β β βββ dom.js # DOM helpers
β βββ components/ # UI components
β β βββ header.js
β β βββ modal.js
β βββ styles/
β βββ main.css # Imported in JS
βββ package.json # npm config
βββ webpack.config.js # Bundler config
βββ .babelrc # Compiler config
Example Component (`components/header.js`):
export function createHeader(title) {
const header = document.createElement('header');
header.innerHTML = `<h1>${title}</h1>`;
return header;
}Main Entry Point (`index.js`):
import { createHeader } from './components/header.js';
import { fetchPosts } from './utils/api.js';
document.body.appendChild(createHeader('My Blog'));
async function init() {
const posts = await fetchPosts();
console.log('Loaded posts:', posts);
}
init();---
β€1
Data Analytics
function oldFetch(url, callback) { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = () => { if (xhr.status === 200) { callback(JSON.parse(xhr.response)); } else { callback(null, xhr.status); } }; xhr.send();β¦
## πΉ Modern Browser APIs
### 1. Web Components
### 2. Intersection Observer
### 3. Web Storage
---
## πΉ Best Practices
1. Use ES modules for modern projects
2. Keep modules focused (single responsibility)
3. Configure tree-shaking to eliminate dead code
4. Use semantic versioning (
5. Set up pre-commit hooks (linting, formatting)
---
### π What's Next?
In Part 7, we'll cover:
β‘οΈ Object-Oriented JavaScript
β‘οΈ Classes & Prototypes
β‘οΈ Design Patterns
#JavaScript #ModernWeb #FrontendDevelopment π
Practice Exercise:
1. Convert an existing script to ES modules
2. Create a Webpack config that bundles JS and CSS
3. Build a custom element with shadow DOM
### 1. Web Components
class MyElement extends HTMLElement {
connectedCallback() {
this.innerHTML = `<h2>Custom Element</h2>`;
}
}
customElements.define('my-element', MyElement);### 2. Intersection Observer
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
}
});
});
document.querySelectorAll('.animate').forEach(el => {
observer.observe(el);
});### 3. Web Storage
// Local Storage (persistent)
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');
// Session Storage (tab-specific)
sessionStorage.setItem('token', 'abc123');
---
## πΉ Best Practices
1. Use ES modules for modern projects
2. Keep modules focused (single responsibility)
3. Configure tree-shaking to eliminate dead code
4. Use semantic versioning (
^1.2.3 in package.json)5. Set up pre-commit hooks (linting, formatting)
---
### π What's Next?
In Part 7, we'll cover:
β‘οΈ Object-Oriented JavaScript
β‘οΈ Classes & Prototypes
β‘οΈ Design Patterns
#JavaScript #ModernWeb #FrontendDevelopment π
Practice Exercise:
1. Convert an existing script to ES modules
2. Create a Webpack config that bundles JS and CSS
3. Build a custom element with shadow DOM
Data Analytics
## πΉ Modern Browser APIs ### 1. Web Components class MyElement extends HTMLElement { connectedCallback() { this.innerHTML = `<h2>Custom Element</h2>`; } } customElements.define('my-element', MyElement); ### 2. Intersection Observer const observerβ¦
# π JavaScript Tutorial - Part 7/10: Object-Oriented JavaScript & Prototypes
#JavaScript #OOP #Prototypes #Classes #DesignPatterns
Welcome to Part 7 of our JavaScript series! This comprehensive lesson will take you deep into JavaScript's object-oriented programming (OOP) system, prototypes, classes, and design patterns.
---
## πΉ JavaScript OOP Fundamentals
### 1. Objects in JavaScript
JavaScript objects are dynamic collections of properties with a hidden
### 2. Factory Functions
Functions that create and return objects.
### 3. Constructor Functions
The traditional way to create object blueprints.
The `new` keyword does:
1. Creates a new empty object
2. Sets
3. Links the object's prototype to constructor's prototype
4. Returns the object (unless constructor returns something else)
---
## πΉ Prototypes & Inheritance
### 1. Prototype Chain
Every JavaScript object has a
### 2. Manual Prototype Inheritance
### 3. Object.create()
Pure prototypal inheritance.
---
## πΉ ES6 Classes
Syntactic sugar over prototypes.
### 1. Class Syntax
### 2. Inheritance with `extends`
### 3. Class Features (ES2022+)
---
## πΉ Property Descriptors
Advanced control over object properties.
### 1. Property Attributes
#JavaScript #OOP #Prototypes #Classes #DesignPatterns
Welcome to Part 7 of our JavaScript series! This comprehensive lesson will take you deep into JavaScript's object-oriented programming (OOP) system, prototypes, classes, and design patterns.
---
## πΉ JavaScript OOP Fundamentals
### 1. Objects in JavaScript
JavaScript objects are dynamic collections of properties with a hidden
[[Prototype]] property.// Object literal (most common)
const person = {
name: 'Ali',
age: 25,
greet() {
console.log(`Hello, I'm ${this.name}`);
}
};
// Properties can be added dynamically
person.country = 'UAE';
delete person.age;
### 2. Factory Functions
Functions that create and return objects.
function createPerson(name, age) {
return {
name,
age,
greet() {
console.log(`Hi, I'm ${this.name}`);
}
};
}
const ali = createPerson('Ali', 25);### 3. Constructor Functions
The traditional way to create object blueprints.
function Person(name, age) {
// Instance properties
this.name = name;
this.age = age;
// Method (created for each instance)
this.greet = function() {
console.log(`Hello, I'm ${this.name}`);
};
}
const ali = new Person('Ali', 25);The `new` keyword does:
1. Creates a new empty object
2. Sets
this to point to the new object3. Links the object's prototype to constructor's prototype
4. Returns the object (unless constructor returns something else)
---
## πΉ Prototypes & Inheritance
### 1. Prototype Chain
Every JavaScript object has a
[[Prototype]] link to another object.// Adding to prototype (shared across instances)
Person.prototype.introduce = function() {
console.log(`My name is ${this.name}, age ${this.age}`);
};
// Prototype chain lookup
ali.introduce(); // Checks ali β Person.prototype β Object.prototype β null
### 2. Manual Prototype Inheritance
function Student(name, age, grade) {
Person.call(this, name, age); // "Super" constructor
this.grade = grade;
}
// Set up prototype chain
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
// Add methods
Student.prototype.study = function() {
console.log(`${this.name} is studying hard!`);
};### 3. Object.create()
Pure prototypal inheritance.
const personProto = {
greet() {
console.log(`Hello from ${this.name}`);
}
};
const ali = Object.create(personProto);
ali.name = 'Ali';---
## πΉ ES6 Classes
Syntactic sugar over prototypes.
### 1. Class Syntax
class Person {
// Constructor (called with 'new')
constructor(name, age) {
this.name = name;
this.age = age;
}
// Instance method
greet() {
console.log(`Hello, I'm ${this.name}`);
}
// Static method
static compareAges(a, b) {
return a.age - b.age;
}
}### 2. Inheritance with `extends`
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // Must call super first
this.grade = grade;
}
study() {
console.log(`${this.name} is studying`);
}
// Override method
greet() {
super.greet(); // Call parent method
console.log(`I'm in grade ${this.grade}`);
}
}### 3. Class Features (ES2022+)
class ModernClass {
// Public field (instance property)
publicField = 1;
// Private field (starts with #)
#privateField = 2;
// Static public field
static staticField = 3;
// Static private field
static #staticPrivateField = 4;
// Private method
#privateMethod() {
return this.#privateField;
}
}---
## πΉ Property Descriptors
Advanced control over object properties.
### 1. Property Attributes
const obj = {};
Object.defineProperty(obj, 'readOnlyProp', {
value: 42,
writable: false, // Can't be changed
enumerable: true, // Shows up in for...in
configurable: false // Can't be deleted/reconfigured
});
Data Analytics
## πΉ Modern Browser APIs ### 1. Web Components class MyElement extends HTMLElement { connectedCallback() { this.innerHTML = `<h2>Custom Element</h2>`; } } customElements.define('my-element', MyElement); ### 2. Intersection Observer const observerβ¦
### 2. Getters & Setters
---
## πΉ Design Patterns in JavaScript
### 1. Singleton Pattern
### 2. Factory Pattern
### 3. Observer Pattern
### 4. Module Pattern
---
## πΉ Practical Example: RPG Character System
---
## πΉ Performance Considerations
### 1. Prototype vs Instance Methods
- Prototype methods are memory efficient (shared)
- Instance methods are created per object
### 2. Object Creation Patterns
| Pattern | Speed | Memory | Features |
|---------|-------|--------|----------|
| Constructor | Fast | Efficient | Full prototype chain |
| Factory | Medium | Less efficient | No
| Class | Fast | Efficient | Clean syntax |
### 3. Property Access Optimization
---
## πΉ Best Practices
1. Use classes for complex hierarchies
2. Favor composition over deep inheritance
3. Keep prototypes lean for performance
4. Use private fields for encapsulation
5. Document your classes with JSDoc
---
### π What's Next?
In Part 8, we'll cover:
β‘οΈ Functional Programming in JavaScript
β‘οΈ Pure Functions & Immutability
β‘οΈ Higher-Order Functions
β‘οΈ Redux Patterns
#JavaScript #OOP #DesignPatterns π
Practice Exercise:
1. Implement a
2. Create a
3. Build an observable
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 1.8 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) / 1.8;
}
}
const temp = new Temperature(25);
console.log(temp.fahrenheit); // 77
temp.fahrenheit = 100;---
## πΉ Design Patterns in JavaScript
### 1. Singleton Pattern
class AppConfig {
constructor() {
if (AppConfig.instance) {
return AppConfig.instance;
}
this.settings = { theme: 'dark' };
AppConfig.instance = this;
}
}
const config1 = new AppConfig();
const config2 = new AppConfig();
console.log(config1 === config2); // true### 2. Factory Pattern
class UserFactory {
static createUser(type) {
switch(type) {
case 'admin':
return new Admin();
case 'customer':
return new Customer();
default:
throw new Error('Invalid user type');
}
}
}### 3. Observer Pattern
class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
(this.events[event] || (this.events[event] = [])).push(listener);
}
emit(event, ...args) {
this.events[event]?.forEach(listener => listener(...args));
}
}
const emitter = new EventEmitter();
emitter.on('login', user => console.log(`${user} logged in`));
emitter.emit('login', 'Ali');### 4. Module Pattern
const CounterModule = (() => {
let count = 0;
return {
increment() {
count++;
},
getCount() {
return count;
}
};
})();---
## πΉ Practical Example: RPG Character System
class Character {
constructor(name, level) {
this.name = name;
this.level = level;
this.health = 100;
}
attack(target) {
const damage = this.level * 2;
target.takeDamage(damage);
console.log(`${this.name} attacks ${target.name} for ${damage} damage`);
}
takeDamage(amount) {
this.health -= amount;
if (this.health <= 0) {
console.log(`${this.name} has been defeated!`);
}
}
}
class Mage extends Character {
constructor(name, level, mana) {
super(name, level);
this.mana = mana;
}
castSpell(target) {
if (this.mana >= 10) {
const damage = this.level * 3;
this.mana -= 10;
target.takeDamage(damage);
console.log(`${this.name} casts a spell on ${target.name}!`);
} else {
console.log("Not enough mana!");
}
}
}
// Usage
const warrior = new Character('Conan', 5);
const wizard = new Mage('Gandalf', 7, 50);
warrior.attack(wizard);
wizard.castSpell(warrior);---
## πΉ Performance Considerations
### 1. Prototype vs Instance Methods
- Prototype methods are memory efficient (shared)
- Instance methods are created per object
### 2. Object Creation Patterns
| Pattern | Speed | Memory | Features |
|---------|-------|--------|----------|
| Constructor | Fast | Efficient | Full prototype chain |
| Factory | Medium | Less efficient | No
instanceof || Class | Fast | Efficient | Clean syntax |
### 3. Property Access Optimization
// Faster (direct property access)
obj.propertyName;
// Slower (dynamic property access)
obj['property' + 'Name'];
---
## πΉ Best Practices
1. Use classes for complex hierarchies
2. Favor composition over deep inheritance
3. Keep prototypes lean for performance
4. Use private fields for encapsulation
5. Document your classes with JSDoc
---
### π What's Next?
In Part 8, we'll cover:
β‘οΈ Functional Programming in JavaScript
β‘οΈ Pure Functions & Immutability
β‘οΈ Higher-Order Functions
β‘οΈ Redux Patterns
#JavaScript #OOP #DesignPatterns π
Practice Exercise:
1. Implement a
Vehicle β Car β ElectricCar hierarchy 2. Create a
BankAccount class with private balance 3. Build an observable
ShoppingCart using the Observer pattern
Data Analytics
# π JavaScript Tutorial - Part 7/10: Object-Oriented JavaScript & Prototypes #JavaScript #OOP #Prototypes #Classes #DesignPatterns Welcome to Part 7 of our JavaScript series! This comprehensive lesson will take you deep into JavaScript's object-orientedβ¦
# π JavaScript Tutorial - Part 8/10: Functional Programming in JavaScript
#JavaScript #FunctionalProgramming #FP #PureFunctions #HigherOrderFunctions
Welcome to Part 8 of our JavaScript series! Today we'll explore functional programming (FP) concepts that will transform how you write JavaScript, making your code more predictable, reusable, and maintainable.
---
## πΉ Core Principles of Functional Programming
### 1. Pure Functions
### 2. Immutability
### 3. Function Composition
---
## πΉ First-Class Functions
### 1. Functions as Arguments
### 2. Returning Functions
### 3. Storing Functions
---
## πΉ Higher-Order Functions
### 1. Array Methods
### 2. Custom HOF Example
---
## πΉ Closures
Functions that remember their lexical scope.
### 1. Basic Closure
### 2. Practical Use Case
---
## πΉ Currying
Transforming a multi-argument function into a sequence of single-argument functions.
---
## πΉ Recursion
### 1. Basic Recursion
### 2. Tail Call Optimization
### 3. Recursive Array Processing
---
#JavaScript #FunctionalProgramming #FP #PureFunctions #HigherOrderFunctions
Welcome to Part 8 of our JavaScript series! Today we'll explore functional programming (FP) concepts that will transform how you write JavaScript, making your code more predictable, reusable, and maintainable.
---
## πΉ Core Principles of Functional Programming
### 1. Pure Functions
// Pure function (same input β same output, no side effects)
function add(a, b) {
return a + b;
}
// Impure function (side effect + depends on external state)
let taxRate = 0.1;
function calculateTax(amount) {
return amount * taxRate; // Depends on external variable
}
### 2. Immutability
// Bad (mutates original array)
const addToCart = (cart, item) => {
cart.push(item); // Mutation!
return cart;
};
// Good (returns new array)
const addToCartFP = (cart, item) => [...cart, item];
### 3. Function Composition
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const toUpperCase = str => str.toUpperCase();
const exclaim = str => `${str}!`;
const shout = compose(exclaim, toUpperCase);
shout('hello'); // "HELLO!"
---
## πΉ First-Class Functions
### 1. Functions as Arguments
const numbers = [1, 2, 3];
// Passing function as argument
numbers.map(num => num * 2); // [2, 4, 6]
### 2. Returning Functions
const createMultiplier = factor => num => num * factor;
const double = createMultiplier(2);
double(5); // 10
### 3. Storing Functions
const mathOps = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
mathOps.add(3, 5); // 8---
## πΉ Higher-Order Functions
### 1. Array Methods
const products = [
{ id: 1, name: 'Laptop', price: 999, inStock: true },
{ id: 2, name: 'Mouse', price: 25, inStock: false }
];
// Transform data
const productNames = products.map(p => p.name);
// Filter data
const availableProducts = products.filter(p => p.inStock);
// Reduce to single value
const totalPrice = products.reduce((sum, p) => sum + p.price, 0);
### 2. Custom HOF Example
function withLogging(fn) {
return (...args) => {
console.log(`Calling with args: ${args}`);
const result = fn(...args);
console.log(`Result: ${result}`);
return result;
};
}
const loggedAdd = withLogging(add);
loggedAdd(3, 5);---
## πΉ Closures
Functions that remember their lexical scope.
### 1. Basic Closure
function createCounter() {
let count = 0;
return () => ++count;
}
const counter = createCounter();
counter(); // 1
counter(); // 2### 2. Practical Use Case
function createApiClient(baseUrl) {
return {
get(endpoint) {
return fetch(`${baseUrl}${endpoint}`).then(res => res.json());
},
post(endpoint, data) {
return fetch(`${baseUrl}${endpoint}`, {
method: 'POST',
body: JSON.stringify(data)
});
}
};
}
const jsonPlaceholder = createApiClient('https://jsonplaceholder.typicode.com');
jsonPlaceholder.get('/posts/1').then(console.log);---
## πΉ Currying
Transforming a multi-argument function into a sequence of single-argument functions.
// Regular function
const add = (a, b, c) => a + b + c;
// Curried version
const curriedAdd = a => b => c => a + b + c;
curriedAdd(1)(2)(3); // 6
// Practical example
const createUser = username => email => password => ({
username,
email,
password
});
const registerUser = createUser('js_dev');
const withEmail = registerUser('[email protected]');
const finalUser = withEmail('secure123');
---
## πΉ Recursion
### 1. Basic Recursion
function factorial(n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}### 2. Tail Call Optimization
function factorial(n, acc = 1) {
return n <= 1 ? acc : factorial(n - 1, n * acc);
}### 3. Recursive Array Processing
function deepMap(arr, fn) {
return arr.map(item =>
Array.isArray(item) ? deepMap(item, fn) : fn(item)
);
}
deepMap([1, [2, [3]]], x => x * 2); // [2, [4, [6]]]---
β€1
Data Analytics
# π JavaScript Tutorial - Part 7/10: Object-Oriented JavaScript & Prototypes #JavaScript #OOP #Prototypes #Classes #DesignPatterns Welcome to Part 7 of our JavaScript series! This comprehensive lesson will take you deep into JavaScript's object-orientedβ¦
## πΉ Practical Example: Redux-like Store
---
## πΉ Best Practices
1. Strive for purity when possible
2. Limit side effects to controlled areas
3. Use immutable data with libraries like Immer
4. Compose small functions into larger ones
5. Document function signatures clearly
---
### π What's Next?
In Part 9, we'll cover:
β‘οΈ Error Handling Strategies
β‘οΈ Debugging Techniques
β‘οΈ Performance Optimization
β‘οΈ Memory Management
#JavaScript #FunctionalProgramming #CleanCode π
Practice Exercise:
1. Convert an imperative function to pure FP style
2. Implement a
3. Create a memoization higher-order function
function createStore(reducer, initialState) {
let state = initialState;
const listeners = [];
const getState = () => state;
const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach(listener => listener());
};
const subscribe = (listener) => {
listeners.push(listener);
return () => {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
};
return { getState, dispatch, subscribe };
}
// Reducer (pure function)
function counterReducer(state = 0, action) {
switch(action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT': return state - 1;
default: return state;
}
}
// Usage
const store = createStore(counterReducer);
store.subscribe(() => console.log(store.getState()));
store.dispatch({ type: 'INCREMENT' }); // Logs: 1---
## πΉ Best Practices
1. Strive for purity when possible
2. Limit side effects to controlled areas
3. Use immutable data with libraries like Immer
4. Compose small functions into larger ones
5. Document function signatures clearly
---
### π What's Next?
In Part 9, we'll cover:
β‘οΈ Error Handling Strategies
β‘οΈ Debugging Techniques
β‘οΈ Performance Optimization
β‘οΈ Memory Management
#JavaScript #FunctionalProgramming #CleanCode π
Practice Exercise:
1. Convert an imperative function to pure FP style
2. Implement a
pipe() function (left-to-right composition) 3. Create a memoization higher-order function
Data Analytics
# π JavaScript Tutorial - Part 8/10: Functional Programming in JavaScript #JavaScript #FunctionalProgramming #FP #PureFunctions #HigherOrderFunctions Welcome to Part 8 of our JavaScript series! Today we'll explore functional programming (FP) concepts thatβ¦
# π JavaScript Tutorial - Part 9/10: Error Handling & Debugging
#JavaScript #Debugging #ErrorHandling #Performance #BestPractices
Welcome to Part 9 of our JavaScript series! Today we'll master professional error handling, debugging techniques, and performance optimization strategies used by senior developers.
---
## πΉ Comprehensive Error Handling
### 1. Error Types in JavaScript
### 2. Custom Error Classes
### 3. Error Boundary Pattern (React-like)
---
## πΉ Advanced Debugging Techniques
### 1. Console Methods Beyond `log()`
### 2. Debugger Statement & Breakpoints
### 3. Source Maps in Production
---
## πΉ Performance Optimization
### 1. Benchmarking Tools
### 2. Memory Leak Detection
Common leak patterns:
### 3. Optimization Techniques
---
## πΉ Memory Management
### 1. Garbage Collection Basics
### 2. WeakMap & WeakSet
---
## πΉ Network Optimization
### 1. Bundle Analysis
### 2. Code Splitting
#JavaScript #Debugging #ErrorHandling #Performance #BestPractices
Welcome to Part 9 of our JavaScript series! Today we'll master professional error handling, debugging techniques, and performance optimization strategies used by senior developers.
---
## πΉ Comprehensive Error Handling
### 1. Error Types in JavaScript
try {
// Potential error code
} catch (error) {
if (error instanceof TypeError) {
console.log("Type error occurred");
} else if (error instanceof ReferenceError) {
console.log("Undefined variable");
} else if (error instanceof RangeError) {
console.log("Value out of range");
} else {
console.log("Unknown error:", error.message);
}
}### 2. Custom Error Classes
class ApiError extends Error {
constructor(url, status, message) {
super(`API call to ${url} failed with ${status}: ${message}`);
this.name = "ApiError";
this.status = status;
this.url = url;
}
}
// Usage
throw new ApiError("/users", 500, "Internal Server Error");### 3. Error Boundary Pattern (React-like)
function ErrorBoundary({ children }) {
const [error, setError] = useState(null);
try {
return children;
} catch (err) {
setError(err);
return <FallbackUI error={error} />;
}
}
// Wrap components
<ErrorBoundary>
<UnstableComponent />
</ErrorBoundary>---
## πΉ Advanced Debugging Techniques
### 1. Console Methods Beyond `log()`
console.table([{id: 1, name: 'Ali'}, {id: 2, name: 'Sarah'}]);
console.group("User Details");
console.log("Name: Ali");
console.log("Age: 25");
console.groupEnd();
console.time("API Call");
await fetchData();
console.timeEnd("API Call"); // Logs execution time### 2. Debugger Statement & Breakpoints
function complexCalculation() {
debugger; // Pauses execution here
// Step through with F10/F11
const result = /* ... */;
return result;
}### 3. Source Maps in Production
// webpack.config.js
module.exports = {
devtool: 'source-map', // Generates .map files
// ...
};
---
## πΉ Performance Optimization
### 1. Benchmarking Tools
// Using performance.now()
const start = performance.now();
expensiveOperation();
const end = performance.now();
console.log(`Operation took ${end - start}ms`);
### 2. Memory Leak Detection
Common leak patterns:
// 1. Accidental globals
function leak() {
leakedVar = 'This is global!'; // Missing var/let/const
}
// 2. Forgotten timers
const intervalId = setInterval(() => {}, 1000);
// Remember to clearInterval(intervalId)
// 3. Detached DOM references
const elements = [];
function storeElement() {
const el = document.createElement('div');
elements.push(el); // Keeps reference after removal
}
### 3. Optimization Techniques
// 1. Debounce rapid events
function debounce(fn, delay) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}
// 2. Web Workers for CPU-intensive tasks
const worker = new Worker('task.js');
worker.postMessage(data);
worker.onmessage = (e) => console.log(e.data);
// 3. Virtualize long lists (react-window, etc.)
---
## πΉ Memory Management
### 1. Garbage Collection Basics
// Circular reference (modern engines handle this)
let obj1 = {};
let obj2 = { ref: obj1 };
obj1.ref = obj2;
// Manual cleanup
let heavyResource = loadResource();
function cleanup() {
heavyResource = null; // Eligible for GC
}
### 2. WeakMap & WeakSet
const weakMap = new WeakMap();
let domNode = document.getElementById('node');
weakMap.set(domNode, { clicks: 0 });
// When domNode is removed, entry is automatically GC'd
---
## πΉ Network Optimization
### 1. Bundle Analysis
npm install -g source-map-explorer
source-map-explorer bundle.js
### 2. Code Splitting
// Dynamic imports
const module = await import('./heavyModule.js');
// React.lazy
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
Data Analytics
# π JavaScript Tutorial - Part 8/10: Functional Programming in JavaScript #JavaScript #FunctionalProgramming #FP #PureFunctions #HigherOrderFunctions Welcome to Part 8 of our JavaScript series! Today we'll explore functional programming (FP) concepts thatβ¦
### 3. Caching Strategies
---
## πΉ Security Best Practices
### 1. Input Sanitization
### 2. Content Security Policy (CSP)
### 3. Secure Authentication
---
## πΉ Practical Example: Robust API Wrapper
---
## πΉ Best Practices Checklist
1. Error Handling
- [ ] Use specific error types
- [ ] Implement global error handlers
- [ ] Validate API responses
2. Debugging
- [ ] Utilize source maps
- [ ] Leverage browser dev tools
- [ ] Add strategic debugger statements
3. Performance
- [ ] Audit bundle size regularly
- [ ] Implement lazy loading
- [ ] Debounce rapid events
4. Security
- [ ] Sanitize user input
- [ ] Use secure token storage
- [ ] Implement CSP headers
---
### π What's Next?
In Final Part 10, we'll cover:
β‘οΈ Modern JavaScript (ES2023+)
β‘οΈ TypeScript Fundamentals
β‘οΈ Advanced Patterns
β‘οΈ Where to Go From Here
#JavaScript #ProfessionalDevelopment #WebDev π
Practice Exercise:
1. Implement error boundaries in a React/Vue app
2. Profile a slow function using Chrome DevTools
3. Create a memory leak and detect it
// Service Worker caching
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});
---
## πΉ Security Best Practices
### 1. Input Sanitization
function sanitizeInput(input) {
return input.replace(/</g, '<').replace(/>/g, '>');
}### 2. Content Security Policy (CSP)
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self' 'unsafe-inline'">
### 3. Secure Authentication
// Never store tokens in localStorage
const auth = {
getToken() {
return window.sessionStorage.getItem('token');
},
setToken(token) {
window.sessionStorage.setItem('token', token);
}
};
---
## πΉ Practical Example: Robust API Wrapper
class ApiClient {
constructor(baseUrl) {
this.baseUrl = baseUrl;
this.cache = new Map();
}
async request(endpoint, options = {}) {
const cacheKey = JSON.stringify({ endpoint, options });
try {
// Cache-first strategy
if (this.cache.has(cacheKey)) {
return this.cache.get(cacheKey);
}
const response = await fetch(`${this.baseUrl}${endpoint}`, {
headers: { 'Content-Type': 'application/json' },
...options
});
if (!response.ok) {
throw new ApiError(
endpoint,
response.status,
await response.text()
);
}
const data = await response.json();
this.cache.set(cacheKey, data); // Cache response
return data;
} catch (error) {
if (error instanceof ApiError) {
console.error(`API Error: ${error.message}`);
} else {
console.error(`Network Error: ${error.message}`);
}
throw error;
}
}
}---
## πΉ Best Practices Checklist
1. Error Handling
- [ ] Use specific error types
- [ ] Implement global error handlers
- [ ] Validate API responses
2. Debugging
- [ ] Utilize source maps
- [ ] Leverage browser dev tools
- [ ] Add strategic debugger statements
3. Performance
- [ ] Audit bundle size regularly
- [ ] Implement lazy loading
- [ ] Debounce rapid events
4. Security
- [ ] Sanitize user input
- [ ] Use secure token storage
- [ ] Implement CSP headers
---
### π What's Next?
In Final Part 10, we'll cover:
β‘οΈ Modern JavaScript (ES2023+)
β‘οΈ TypeScript Fundamentals
β‘οΈ Advanced Patterns
β‘οΈ Where to Go From Here
#JavaScript #ProfessionalDevelopment #WebDev π
Practice Exercise:
1. Implement error boundaries in a React/Vue app
2. Profile a slow function using Chrome DevTools
3. Create a memory leak and detect it
Data Analytics
# π JavaScript Tutorial - Part 9/10: Error Handling & Debugging #JavaScript #Debugging #ErrorHandling #Performance #BestPractices Welcome to Part 9 of our JavaScript series! Today we'll master professional error handling, debugging techniques, and performanceβ¦
# π JavaScript Tutorial - Part 10/10: Modern JavaScript & Beyond
#JavaScript #ES2023 #TypeScript #AdvancedPatterns #WebDev
Welcome to the final part of our comprehensive JavaScript series! This ultimate lesson explores cutting-edge JavaScript features, TypeScript fundamentals, advanced patterns, and pathways for continued learning.
---
## πΉ Modern JavaScript Features (ES2023+)
### 1. Top-Level Await (ES2022)
### 2. Array Find from Last (ES2023)
### 3. Hashbang Support (ES2023)
### 4. WeakRef & FinalizationRegistry (ES2021)
### 5. Error Cause (ES2022)
---
## πΉ TypeScript Fundamentals
### 1. Basic Types
### 2. Interfaces & Types
### 3. Generics
### 4. Type Inference & Utility Types
---
## πΉ Advanced Patterns
### 1. Dependency Injection
### 2. Proxy API
### 3. Observable Pattern
---
## πΉ Web Components
### 1. Custom Elements
### 2. Template Literals for HTML
---
## πΉ Performance Patterns
### 1. Virtualization
#JavaScript #ES2023 #TypeScript #AdvancedPatterns #WebDev
Welcome to the final part of our comprehensive JavaScript series! This ultimate lesson explores cutting-edge JavaScript features, TypeScript fundamentals, advanced patterns, and pathways for continued learning.
---
## πΉ Modern JavaScript Features (ES2023+)
### 1. Top-Level Await (ES2022)
// Module.js
const data = await fetch('https://api.example.com/data');
export { data };
// No need for async wrapper!
### 2. Array Find from Last (ES2023)
const numbers = [10, 20, 30, 20, 40];
numbers.findLast(n => n === 20); // 20 (last occurrence)
numbers.findLastIndex(n => n === 20); // 3
### 3. Hashbang Support (ES2023)
#!/usr/bin/env node
// Now executable directly via ./script.js
console.log('Hello from executable JS!');
### 4. WeakRef & FinalizationRegistry (ES2021)
const weakRef = new WeakRef(domElement);
const registry = new FinalizationRegistry(heldValue => {
console.log(`${heldValue} was garbage collected`);
});
registry.register(domElement, "DOM Element");
### 5. Error Cause (ES2022)
try {
await fetchData();
} catch (error) {
throw new Error('Processing failed', { cause: error });
}---
## πΉ TypeScript Fundamentals
### 1. Basic Types
let username: string = "Ali";
let age: number = 25;
let isActive: boolean = true;
let scores: number[] = [90, 85, 95];
let user: { name: string; age?: number } = { name: "Ali" };
### 2. Interfaces & Types
interface User {
id: number;
name: string;
email: string;
}
type Admin = User & {
permissions: string[];
};
function createUser(user: User): Admin {
// ...
}### 3. Generics
function identity<T>(arg: T): T {
return arg;
}
const result = identity<string>("Hello");### 4. Type Inference & Utility Types
const user = {
name: "Ali",
age: 25
}; // Type inferred as { name: string; age: number }
type PartialUser = Partial<typeof user>;
type ReadonlyUser = Readonly<typeof user>;---
## πΉ Advanced Patterns
### 1. Dependency Injection
class Database {
constructor(private connection: Connection) {}
query(sql: string) {
return this.connection.execute(sql);
}
}
const db = new Database(new MySQLConnection());### 2. Proxy API
const validator = {
set(target, property, value) {
if (property === 'age' && typeof value !== 'number') {
throw new TypeError('Age must be a number');
}
target[property] = value;
return true;
}
};
const user = new Proxy({}, validator);
user.age = 25; // OK
user.age = "25"; // Throws error### 3. Observable Pattern
class Observable<T> {
private subscribers: ((value: T) => void)[] = [];
subscribe(callback: (value: T) => void) {
this.subscribers.push(callback);
}
next(value: T) {
this.subscribers.forEach(cb => cb(value));
}
}
const clicks = new Observable<MouseEvent>();
clicks.subscribe(e => console.log(e.clientX));
document.addEventListener('click', e => clicks.next(e));---
## πΉ Web Components
### 1. Custom Elements
class PopupAlert extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
.alert { /* styles */ }
</style>
<div class="alert">
<slot></slot>
</div>
`;
}
}
customElements.define('popup-alert', PopupAlert);### 2. Template Literals for HTML
function html(strings, ...values) {
let str = '';
strings.forEach((string, i) => {
str += string + (values[i] || '');
});
const template = document.createElement('template');
template.innerHTML = str;
return template.content;
}
const fragment = html`<div>Hello ${name}</div>`;---
## πΉ Performance Patterns
### 1. Virtualization
function renderVirtualList(items, container, renderItem) {
const visibleItems = getVisibleItems(items, container);
container.replaceChildren(
...visibleItems.map(item => renderItem(item))
);
}β€1
Data Analytics
# π JavaScript Tutorial - Part 9/10: Error Handling & Debugging #JavaScript #Debugging #ErrorHandling #Performance #BestPractices Welcome to Part 9 of our JavaScript series! Today we'll master professional error handling, debugging techniques, and performanceβ¦
### 2. WebAssembly Integration
### 3. Worker Pools
---
## πΉ Where to Go From Here?
### 1. Recommended Learning Paths
- Frontend Masters: Advanced JavaScript courses
- TypeScript Docs: Full language reference
- ECMAScript Proposals: GitHub tc39/proposals
### 2. Must-Read Books
- "JavaScript: The Definitive Guide" by David Flanagan
- "Eloquent JavaScript" by Marijn Haverbeke
- "Effective TypeScript" by Dan Vanderkam
### 3. Open Source Contribution
- First Timers Only: Beginner-friendly issues
- Good First Issue: Curated list for new contributors
- Your Favorite Libraries: Check their GitHub issues
### 4. Project Ideas
1. Build a compiler (Babel plugin)
2. Create a state management library
3. Develop a browser extension
4. Contribute to Node.js core
5. Build a WebGL visualization
---
## πΉ Final Project: Full-Stack TypeScript App
---
## πΉ JavaScript Ecosystem Checklist
1. Master the Browser API
- DOM, Fetch, Storage, Workers, etc.
2. Learn Node.js Internals
- Event Loop, Streams, Clusters
3. Explore Build Tools
- Webpack, Vite, Rollup, esbuild
4. Understand Testing
- Jest, Vitest, Cypress, Playwright
5. Follow Trends
- Web Components, WASM, Edge Computing
---
### π Congratulations on Completing the Series!
You've now covered:
1. JavaScript Fundamentals
2. Control Flow & Functions
3. Arrays & Objects
4. DOM Manipulation
5. Asynchronous JS
6. Modules & Tooling
7. OOP & Prototypes
8. Functional Programming
9. Error Handling & Debugging
10. Modern JS & Beyond
#JavaScriptMastery #FullStackDeveloper #CareerGrowth π
Final Challenge:
1. Build a TS library with tests and docs
2. Optimize a slow web app using profiling
3. Contribute to an open-source project
Remember: The best way to learn is by building real projects! Keep coding! π¨βπ»π©βπ»
// Load WASM module
WebAssembly.instantiateStreaming(fetch('module.wasm'))
.then(obj => {
const result = obj.instance.exports.add(1, 2);
console.log(result); // 3
});
### 3. Worker Pools
class WorkerPool {
constructor(size = navigator.hardwareConcurrency) {
this.workers = Array(size).fill().map(() => new Worker('task.js'));
this.queue = [];
}
execute(data) {
return new Promise((resolve) => {
const worker = this.workers.pop() || this.queue.push(resolve);
if (worker) this.runTask(worker, data, resolve);
});
}
runTask(worker, data, resolve) {
worker.onmessage = (e) => {
resolve(e.data);
this.workers.push(worker);
if (this.queue.length) {
this.runTask(worker, this.queue.shift());
}
};
worker.postMessage(data);
}
}---
## πΉ Where to Go From Here?
### 1. Recommended Learning Paths
- Frontend Masters: Advanced JavaScript courses
- TypeScript Docs: Full language reference
- ECMAScript Proposals: GitHub tc39/proposals
### 2. Must-Read Books
- "JavaScript: The Definitive Guide" by David Flanagan
- "Eloquent JavaScript" by Marijn Haverbeke
- "Effective TypeScript" by Dan Vanderkam
### 3. Open Source Contribution
- First Timers Only: Beginner-friendly issues
- Good First Issue: Curated list for new contributors
- Your Favorite Libraries: Check their GitHub issues
### 4. Project Ideas
1. Build a compiler (Babel plugin)
2. Create a state management library
3. Develop a browser extension
4. Contribute to Node.js core
5. Build a WebGL visualization
---
## πΉ Final Project: Full-Stack TypeScript App
// Backend (Node.js + Express)
import express from 'express';
import { createUser, getUsers } from './database';
const app = express();
app.use(express.json());
app.get('/users', async (req, res) => {
const users = await getUsers();
res.json(users);
});
app.post('/users', async (req, res) => {
const newUser = await createUser(req.body);
res.status(201).json(newUser);
});
// Frontend (React + TypeScript)
interface User {
id: string;
name: string;
email: string;
}
function UserList() {
const [users, setUsers] = useState<User[]>([]);
useEffect(() => {
fetch('/users')
.then(res => res.json())
.then(data => setUsers(data));
}, []);
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
---
## πΉ JavaScript Ecosystem Checklist
1. Master the Browser API
- DOM, Fetch, Storage, Workers, etc.
2. Learn Node.js Internals
- Event Loop, Streams, Clusters
3. Explore Build Tools
- Webpack, Vite, Rollup, esbuild
4. Understand Testing
- Jest, Vitest, Cypress, Playwright
5. Follow Trends
- Web Components, WASM, Edge Computing
---
### π Congratulations on Completing the Series!
You've now covered:
1. JavaScript Fundamentals
2. Control Flow & Functions
3. Arrays & Objects
4. DOM Manipulation
5. Asynchronous JS
6. Modules & Tooling
7. OOP & Prototypes
8. Functional Programming
9. Error Handling & Debugging
10. Modern JS & Beyond
#JavaScriptMastery #FullStackDeveloper #CareerGrowth π
Final Challenge:
1. Build a TS library with tests and docs
2. Optimize a slow web app using profiling
3. Contribute to an open-source project
Remember: The best way to learn is by building real projects! Keep coding! π¨βπ»π©βπ»
β€2
Forwarded from Machine Learning with Python
This channels is for Programmers, Coders, Software Engineers.
0οΈβ£ Python
1οΈβ£ Data Science
2οΈβ£ Machine Learning
3οΈβ£ Data Visualization
4οΈβ£ Artificial Intelligence
5οΈβ£ Data Analysis
6οΈβ£ Statistics
7οΈβ£ Deep Learning
8οΈβ£ programming Languages
β
https://t.iss.one/addlist/8_rRW2scgfRhOTc0
β
https://t.iss.one/Codeprogrammer
Please open Telegram to view this post
VIEW IN TELEGRAM
π Kafka Tutorial β Part 1: Introduction to Apache Kafka β The Ultimate Guide for Beginners
Let's Start: https://hackmd.io/@husseinsheikho/Kafka-part1
Let's Start: https://hackmd.io/@husseinsheikho/Kafka-part1
#ApacheKafka #KafkaTutorial #StreamingData #BigData #RealTimeProcessing #EventDrivenArchitecture #KafkaBasics
βοΈ Our Telegram channels: https://t.iss.one/addlist/0f6vfFbEMdAwODBkπ± Our WhatsApp channel: https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
Please open Telegram to view this post
VIEW IN TELEGRAM
β€2