Data Analytics
# 📚 Java Programming Language – Part 8/10: Exception Handling #Java #Exceptions #ErrorHandling #Programming Welcome to Part 8 of our Java series! Today we'll master how to handle errors and exceptional situations in Java programs. --- ## 🔹 What are Exceptions?…
# 📚 Java Programming Language – Part 9/10: Collections Framework
#Java #Collections #DataStructures #Programming
Welcome to Part 9 of our Java series! Today we'll explore the powerful Collections Framework - essential for handling groups of objects efficiently.
---
## 🔹 Collections Framework Overview
The Java Collections Framework provides:
- Interfaces (List, Set, Map, etc.)
- Implementations (ArrayList, HashSet, HashMap, etc.)
- Algorithms (Searching, Sorting, Shuffling)

---
## 🔹 Core Interfaces
| Interface | Denoscription | Key Implementations |
|-----------|-------------|---------------------|
|
|
|
|
---
## 🔹 List Implementations
### 1. ArrayList
### 2. LinkedList
---
## 🔹 Set Implementations
### 1. HashSet (Unordered)
### 2. TreeSet (Sorted)
---
## 🔹 Map Implementations
### 1. HashMap
### 2. TreeMap (Sorted by keys)
---
## 🔹 Iterating Collections
### 1. For-Each Loop
### 2. Iterator
### 3. forEach() Method (Java 8+)
---
## 🔹 Collections Utility Class
Powerful static methods for collections:
---
#Java #Collections #DataStructures #Programming
Welcome to Part 9 of our Java series! Today we'll explore the powerful Collections Framework - essential for handling groups of objects efficiently.
---
## 🔹 Collections Framework Overview
The Java Collections Framework provides:
- Interfaces (List, Set, Map, etc.)
- Implementations (ArrayList, HashSet, HashMap, etc.)
- Algorithms (Searching, Sorting, Shuffling)

---
## 🔹 Core Interfaces
| Interface | Denoscription | Key Implementations |
|-----------|-------------|---------------------|
|
List | Ordered collection (allows duplicates) | ArrayList, LinkedList ||
Set | Unique elements (no duplicates) | HashSet, TreeSet ||
Queue | FIFO ordering | LinkedList, PriorityQueue ||
Map | Key-value pairs | HashMap, TreeMap |---
## 🔹 List Implementations
### 1. ArrayList
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add(1, "Charlie"); // Insert at index 1
System.out.println(names); // [Alice, Charlie, Bob]
System.out.println(names.get(0)); // Alice
### 2. LinkedList
List<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.addFirst(5); // Add to beginning
numbers.addLast(20); // Add to end
System.out.println(numbers); // [5, 10, 20]
---
## 🔹 Set Implementations
### 1. HashSet (Unordered)
Set<String> uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Alice"); // Duplicate ignored
System.out.println(uniqueNames); // [Alice, Bob] (order may vary)
### 2. TreeSet (Sorted)
Set<Integer> sortedNumbers = new TreeSet<>();
sortedNumbers.add(5);
sortedNumbers.add(2);
sortedNumbers.add(8);
System.out.println(sortedNumbers); // [2, 5, 8]
---
## 🔹 Map Implementations
### 1. HashMap
Map<String, Integer> ageMap = new HashMap<>();
ageMap.put("Alice", 25);
ageMap.put("Bob", 30);
ageMap.put("Alice", 26); // Overwrites previous value
System.out.println(ageMap.get("Alice")); // 26
System.out.println(ageMap.containsKey("Bob")); // true
### 2. TreeMap (Sorted by keys)
Map<String, String> sortedMap = new TreeMap<>();
sortedMap.put("Orange", "Fruit");
sortedMap.put("Carrot", "Vegetable");
sortedMap.put("Apple", "Fruit");
System.out.println(sortedMap);
// {Apple=Fruit, Carrot=Vegetable, Orange=Fruit}
---
## 🔹 Iterating Collections
### 1. For-Each Loop
List<String> colors = List.of("Red", "Green", "Blue");
for (String color : colors) {
System.out.println(color);
}### 2. Iterator
Set<Integer> numbers = new HashSet<>(Set.of(1, 2, 3));
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
### 3. forEach() Method (Java 8+)
Map<String, Integer> map = Map.of("A", 1, "B", 2);
map.forEach((key, value) ->
System.out.println(key + ": " + value));---
## 🔹 Collections Utility Class
Powerful static methods for collections:
List<Integer> numbers = new ArrayList<>(List.of(3, 1, 4, 1, 5));
Collections.sort(numbers); // [1, 1, 3, 4, 5]
Collections.reverse(numbers); // [5, 4, 3, 1, 1]
Collections.shuffle(numbers); // Random order
Collections.frequency(numbers, 1); // 2
---
Data Analytics
# 📚 Java Programming Language – Part 8/10: Exception Handling #Java #Exceptions #ErrorHandling #Programming Welcome to Part 8 of our Java series! Today we'll master how to handle errors and exceptional situations in Java programs. --- ## 🔹 What are Exceptions?…
## 🔹 Practical Example: Student Grade System
---
## 🔹 Best Practices
1. Use interface references (
2. Initialize with capacity for large collections
3. Use immutable collections when possible (
4. Choose the right collection based on needs
5. Consider thread safety (
---
### 📌 What's Next?
In Final Part 10, we'll cover:
➡️ Java Streams API
➡️ Lambda Expressions
➡️ Modern Java Features
#JavaCollections #DataStructures #Programming🚀
public class GradeSystem {
private Map<String, List<Integer>> studentGrades = new HashMap<>();
public void addGrade(String student, int grade) {
studentGrades.computeIfAbsent(student, k -> new ArrayList<>()).add(grade);
}
public double getAverage(String student) {
return studentGrades.getOrDefault(student, List.of())
.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0.0);
}
public Set<String> getTopStudents(double minAverage) {
return studentGrades.entrySet().stream()
.filter(entry -> getAverage(entry.getKey()) >= minAverage)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
}
// Usage:
GradeSystem system = new GradeSystem();
system.addGrade("Alice", 90);
system.addGrade("Alice", 95);
system.addGrade("Bob", 80);
System.out.println(system.getAverage("Alice")); // 92.5
System.out.println(system.getTopStudents(85)); // [Alice]---
## 🔹 Best Practices
1. Use interface references (
List instead of ArrayList)2. Initialize with capacity for large collections
3. Use immutable collections when possible (
List.of())4. Choose the right collection based on needs
5. Consider thread safety (
CopyOnWriteArrayList, ConcurrentHashMap)---
### 📌 What's Next?
In Final Part 10, we'll cover:
➡️ Java Streams API
➡️ Lambda Expressions
➡️ Modern Java Features
#JavaCollections #DataStructures #Programming
Please open Telegram to view this post
VIEW IN TELEGRAM
Data Analytics
# 📚 Java Programming Language – Part 9/10: Collections Framework #Java #Collections #DataStructures #Programming Welcome to Part 9 of our Java series! Today we'll explore the powerful Collections Framework - essential for handling groups of objects efficiently.…
# 📚 Java Programming Language – Part 10/10: Streams & Modern Java Features
#Java #Streams #Lambda #ModernJava #Programming
Welcome to the final part of our Java series! Today we'll explore powerful modern Java features including Streams API and Lambda expressions.
---
## 🔹 Lambda Expressions
Concise way to implement functional interfaces.
### 1. Basic Syntax
### 2. Lambda Variations
---
## 🔹 Functional Interfaces
Single abstract method interfaces work with lambdas.
### 1. Common Functional Interfaces
| Interface | Method | Example Use |
|----------------|----------------|---------------------------|
|
|
|
|
### 2. Practical Example
---
## 🔹 Streams API
Powerful way to process collections functionally.
### 1. Stream Pipeline
### 2. Common Stream Operations
| Operation | Type | Example |
|-----------|------|---------|
|
|
|
|
|
|
---
## 🔹 Method References
Shortcut for lambda expressions.
### 1. Types of Method References
---
## 🔹 Optional Class
Handle null values safely.
### 1. Basic Usage
### 2. Practical Example
---
## 🔹 Modern Java Features (Java 8-17)
### 1. Records (Java 16)
### 2. Pattern Matching (Java 16)
### 3. Text Blocks (Java 15)
#Java #Streams #Lambda #ModernJava #Programming
Welcome to the final part of our Java series! Today we'll explore powerful modern Java features including Streams API and Lambda expressions.
---
## 🔹 Lambda Expressions
Concise way to implement functional interfaces.
### 1. Basic Syntax
// Traditional way
Runnable r1 = new Runnable() {
public void run() {
System.out.println("Running!");
}
};
// Lambda equivalent
Runnable r2 = () -> System.out.println("Running!");
### 2. Lambda Variations
// No parameters
() -> System.out.println("Hello")
// Single parameter
name -> System.out.println("Hello " + name)
// Multiple parameters
(a, b) -> a + b
// With return and body
(x, y) -> {
int sum = x + y;
return sum * 2;
}
---
## 🔹 Functional Interfaces
Single abstract method interfaces work with lambdas.
### 1. Common Functional Interfaces
| Interface | Method | Example Use |
|----------------|----------------|---------------------------|
|
Predicate<T> | test(T t) | Filter elements ||
Function<T,R>| apply(T t) | Transform elements ||
Consumer<T> | accept(T t) | Perform actions ||
Supplier<T> | get() | Generate values |### 2. Practical Example
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// Using Predicate
Predicate<String> startsWithA = name -> name.startsWith("A");
names.stream().filter(startsWithA).forEach(System.out::println);
// Using Function
Function<String, Integer> nameLength = String::length;
names.stream().map(nameLength).forEach(System.out::println);---
## 🔹 Streams API
Powerful way to process collections functionally.
### 1. Stream Pipeline
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream() // Source
.filter(n -> n % 2 == 0) // Intermediate operation
.map(n -> n * 2) // Intermediate operation
.reduce(0, Integer::sum); // Terminal operation
System.out.println(sum); // 12 (2*2 + 4*2)
### 2. Common Stream Operations
| Operation | Type | Example |
|-----------|------|---------|
|
filter | Intermediate | .filter(n -> n > 5) ||
map | Intermediate | .map(String::toUpperCase) ||
sorted | Intermediate | .sorted(Comparator.reverseOrder()) ||
forEach | Terminal | .forEach(System.out::println) ||
collect | Terminal | .collect(Collectors.toList()) ||
reduce | Terminal | .reduce(0, Integer::sum) |---
## 🔹 Method References
Shortcut for lambda expressions.
### 1. Types of Method References
// Static method
Function<String, Integer> parser = Integer::parseInt;
// Instance method of object
Consumer<String> printer = System.out::println;
// Instance method of class
Function<String, String> upper = String::toUpperCase;
// Constructor
Supplier<List<String>> listSupplier = ArrayList::new;
---
## 🔹 Optional Class
Handle null values safely.
### 1. Basic Usage
Optional<String> name = Optional.ofNullable(getName());
String result = name
.map(String::toUpperCase)
.orElse("DEFAULT");
System.out.println(result);
### 2. Practical Example
public class UserService {
public Optional<User> findUser(String id) {
// May return null
return Optional.ofNullable(database.findUser(id));
}
}
// Usage:
userService.findUser("123")
.ifPresentOrElse(
user -> System.out.println("Found: " + user),
() -> System.out.println("User not found")
);---
## 🔹 Modern Java Features (Java 8-17)
### 1. Records (Java 16)
public record Person(String name, int age) {}
// Automatically generates:
// - Constructor
// - Getters
// - equals(), hashCode(), toString()### 2. Pattern Matching (Java 16)
if (obj instanceof String s) {
System.out.println(s.length());
}### 3. Text Blocks (Java 15)
String json = """
{
"name": "Alice",
"age": 25
}
""";
❤1👍1
Data Analytics
# 📚 Java Programming Language – Part 9/10: Collections Framework #Java #Collections #DataStructures #Programming Welcome to Part 9 of our Java series! Today we'll explore the powerful Collections Framework - essential for handling groups of objects efficiently.…
### 4. Switch Expressions (Java 14)
---
## 🔹 Practical Example: Employee Processing
---
## 🔹 Best Practices
1. Prefer immutability with records and unmodifiable collections
2. Use Optional instead of null checks
3. Favor functional style with streams for data processing
4. Keep lambdas short and readable
5. Adopt modern features gradually in existing codebases
---
### 🎉 Congratulations!
You've completed our 10-part Java series! Here's what we covered:
1. Java Basics
2. Operators & Control Flow
3. Methods & Functions
4. OOP Concepts
5. Inheritance & Polymorphism
6. Interfaces & Abstract Classes
7. Packages & Access Modifiers
8. Exception Handling
9. Collections Framework
10. Streams & Modern Features
#JavaProgramming #CompleteCourse #ModernJava 🚀
What's next?
➡️ Build real projects
➡️ Explore frameworks (Spring, Jakarta EE)
➡️ Learn design patterns
➡️ Contribute to open source
Happy coding!👨💻 👩💻
String dayType = switch (day) {
case "Mon", "Tue", "Wed", "Thu", "Fri" -> "Weekday";
case "Sat", "Sun" -> "Weekend";
default -> throw new IllegalArgumentException();
};---
## 🔹 Practical Example: Employee Processing
public class Employee {
private String name;
private String department;
private double salary;
// Constructor, getters
}
List<Employee> employees = // ... initialized list
// Stream processing example
Map<String, Double> avgSalaryByDept = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.averagingDouble(Employee::getSalary)
));
// Modern Java features
List<String> highEarners = employees.stream()
.filter(e -> e.salary() > 100000)
.map(Employee::name)
.sorted()
.toList(); // Java 16+ toList()
System.out.println(avgSalaryByDept);
System.out.println(highEarners);---
## 🔹 Best Practices
1. Prefer immutability with records and unmodifiable collections
2. Use Optional instead of null checks
3. Favor functional style with streams for data processing
4. Keep lambdas short and readable
5. Adopt modern features gradually in existing codebases
---
### 🎉 Congratulations!
You've completed our 10-part Java series! Here's what we covered:
1. Java Basics
2. Operators & Control Flow
3. Methods & Functions
4. OOP Concepts
5. Inheritance & Polymorphism
6. Interfaces & Abstract Classes
7. Packages & Access Modifiers
8. Exception Handling
9. Collections Framework
10. Streams & Modern Features
#JavaProgramming #CompleteCourse #ModernJava 🚀
What's next?
➡️ Build real projects
➡️ Explore frameworks (Spring, Jakarta EE)
➡️ Learn design patterns
➡️ Contribute to open source
Happy coding!
Please open Telegram to view this post
VIEW IN TELEGRAM
# 📚 100 Essential Java Interview Questions
#Java #Interview #Programming #OOP #Collections #Multithreading
---
## 🔹 Core Java (20 Questions)
1. What is JVM, JRE, and JDK?
2. Explain
3. Difference between == and
4. What are Java primitives? List all 8.
5. Explain autoboxing/unboxing
6. What are varargs?
7. Difference between
8. What are immutable objects? How to create them?
9. Explain
10. What are annotations? Common built-in annotations?
11. Difference between
12. What is
13. Can we override static methods?
14. What is method overloading vs overriding?
15. What is
16. Explain pass-by-value in Java
17. What are wrapper classes? Why needed?
18. What is enum? When to use?
19. Difference between
20. What is type casting? Implicit vs explicit
---
## 🔹 OOP Concepts (15 Questions)
21. 4 Pillars of OOP with examples
22. What is abstraction vs encapsulation?
23. Difference between abstract class and interface (Java 8+)
24. Can an interface have constructors?
25. What is polymorphism? Runtime vs compile-time
26. What is method hiding?
27. What is composition vs inheritance?
28. What is the Liskov Substitution Principle?
29. How to achieve multiple inheritance in Java?
30. What is a singleton? Thread-safe implementation
31. What is a factory pattern?
32. What is a marker interface?
33. What is a POJO?
34. What is the
35. What is object cloning? Shallow vs deep copy
---
## 🔹 Collections Framework (15 Questions)
36. Collections hierarchy diagram explanation
37. Difference between
38.
39.
40.
41. How
42. What is hashing? Hashcode/equals contract
43. What is
44. Fail-fast vs fail-safe iterators
45. How to make collections immutable?
46. What is
47. Difference between
48. What are Java 8 stream APIs?
49.
50. What are collectors? Common collectors
---
## 🔹 Exception Handling (10 Questions)
51. Exception hierarchy in Java
52. Checked vs unchecked exceptions
53. What is
54. Can we have
55. What is exception propagation?
56. Difference between
57. How to create custom exceptions?
58. What is
59. Best practices for exception handling
60. What is
---
## 🔹 Multithreading (15 Questions)
61. Process vs thread
62. Ways to create threads
63.
64. Thread lifecycle states
65. What is synchronization?
66.
67. What are volatile variables?
68. What is deadlock? How to avoid?
69. What is thread starvation?
70.
71. What is thread pool? Executor framework
72. What is
73. What is atomic variable?
74. What is
75. Concurrent collections in Java
---
## 🔹 Java 8+ Features (10 Questions)
76. What are lambda expressions?
77. Functional interfaces in Java
78. Method references types
79.
80. Stream API operations
81.
82. What are default methods?
83. What are static methods in interfaces?
84. New Date/Time API benefits
85. Records and sealed classes
---
## 🔹 JVM & Performance (10 Questions)
86. JVM architecture overview
87. What is classloader?
88. What is bytecode?
89. What is JIT compiler?
90. Heap memory structure
91. What is garbage collection? Types of GC
92.
93. How to handle memory leaks?
94. What is
95. JVM tuning parameters
---
#Java #Interview #Programming #OOP #Collections #Multithreading
---
## 🔹 Core Java (20 Questions)
1. What is JVM, JRE, and JDK?
2. Explain
public static void main(String[] args) 3. Difference between == and
.equals()? 4. What are Java primitives? List all 8.
5. Explain autoboxing/unboxing
6. What are varargs?
7. Difference between
String, StringBuilder, and StringBuffer 8. What are immutable objects? How to create them?
9. Explain
final, finally, and finalize 10. What are annotations? Common built-in annotations?
11. Difference between
throw and throws 12. What is
static keyword? 13. Can we override static methods?
14. What is method overloading vs overriding?
15. What is
this and super keywords? 16. Explain pass-by-value in Java
17. What are wrapper classes? Why needed?
18. What is enum? When to use?
19. Difference between
instanceof and getClass() 20. What is type casting? Implicit vs explicit
---
## 🔹 OOP Concepts (15 Questions)
21. 4 Pillars of OOP with examples
22. What is abstraction vs encapsulation?
23. Difference between abstract class and interface (Java 8+)
24. Can an interface have constructors?
25. What is polymorphism? Runtime vs compile-time
26. What is method hiding?
27. What is composition vs inheritance?
28. What is the Liskov Substitution Principle?
29. How to achieve multiple inheritance in Java?
30. What is a singleton? Thread-safe implementation
31. What is a factory pattern?
32. What is a marker interface?
33. What is a POJO?
34. What is the
instanceof operator used for? 35. What is object cloning? Shallow vs deep copy
---
## 🔹 Collections Framework (15 Questions)
36. Collections hierarchy diagram explanation
37. Difference between
List, Set, and Map 38.
ArrayList vs LinkedList 39.
HashSet vs TreeSet 40.
HashMap vs HashTable vs ConcurrentHashMap 41. How
HashMap works internally? 42. What is hashing? Hashcode/equals contract
43. What is
Comparable vs Comparator? 44. Fail-fast vs fail-safe iterators
45. How to make collections immutable?
46. What is
PriorityQueue? 47. Difference between
Iterator and ListIterator 48. What are Java 8 stream APIs?
49.
map() vs flatMap() 50. What are collectors? Common collectors
---
## 🔹 Exception Handling (10 Questions)
51. Exception hierarchy in Java
52. Checked vs unchecked exceptions
53. What is
try-with-resources? 54. Can we have
try without catch? 55. What is exception propagation?
56. Difference between
throw and throws 57. How to create custom exceptions?
58. What is
Error vs Exception? 59. Best practices for exception handling
60. What is
@SuppressWarnings? ---
## 🔹 Multithreading (15 Questions)
61. Process vs thread
62. Ways to create threads
63.
Runnable vs Callable 64. Thread lifecycle states
65. What is synchronization?
66.
synchronized keyword usage 67. What are volatile variables?
68. What is deadlock? How to avoid?
69. What is thread starvation?
70.
wait(), notify(), notifyAll() methods 71. What is thread pool? Executor framework
72. What is
Future and CompletableFuture? 73. What is atomic variable?
74. What is
ThreadLocal? 75. Concurrent collections in Java
---
## 🔹 Java 8+ Features (10 Questions)
76. What are lambda expressions?
77. Functional interfaces in Java
78. Method references types
79.
Optional class purpose 80. Stream API operations
81.
map() vs flatMap() 82. What are default methods?
83. What are static methods in interfaces?
84. New Date/Time API benefits
85. Records and sealed classes
---
## 🔹 JVM & Performance (10 Questions)
86. JVM architecture overview
87. What is classloader?
88. What is bytecode?
89. What is JIT compiler?
90. Heap memory structure
91. What is garbage collection? Types of GC
92.
String pool concept 93. How to handle memory leaks?
94. What is
OutOfMemoryError? Common causes 95. JVM tuning parameters
---
## 🔹 Advanced Topics (5 Questions)
96. What is reflection? Use cases
97. What are Java modules?
98. What is serialization? How to customize?
99. What are Java generics? Type erasure
100. What is the module system in Java 9?
---
### 📌 Bonus Tips for Interviews
✔️ Always explain with code examples
✔️ Mention real-world applications
✔️ Compare alternatives (e.g., ArrayList vs LinkedList)
✔️ Discuss performance implications
✔️ Be honest about what you don't know
#JavaInterview #CodingInterview #TechPrep 🚀
Practice these well and you'll ace any Java interview!
96. What is reflection? Use cases
97. What are Java modules?
98. What is serialization? How to customize?
99. What are Java generics? Type erasure
100. What is the module system in Java 9?
---
### 📌 Bonus Tips for Interviews
✔️ Always explain with code examples
✔️ Mention real-world applications
✔️ Compare alternatives (e.g., ArrayList vs LinkedList)
✔️ Discuss performance implications
✔️ Be honest about what you don't know
#JavaInterview #CodingInterview #TechPrep 🚀
Practice these well and you'll ace any Java interview!
❤1
# 📚 JavaScript Tutorial - Part 1/10: The Complete Beginner's Guide
#JavaScript #WebDev #Programming #BeginnerFriendly
Welcome to Part 1 of our comprehensive 10-part JavaScript series! This tutorial is designed for absolute beginners with detailed explanations and practical examples.
---
## 🔹 What is JavaScript?
JavaScript is a high-level, interpreted programming language that:
- Runs in web browsers (client-side)
- Can also run on servers (Node.js)
- Adds interactivity to websites
- Works with HTML/CSS to create dynamic web pages
Key Features:
✔️ Event-driven programming
✔️ Supports object-oriented and functional styles
✔️ Dynamically typed
✔️ Asynchronous operations (callbacks, promises)
---
## 🔹 JavaScript vs Other Languages
| Feature | JavaScript | Python | Java |
|---------------|---------------|---------------|---------------|
| Typing | Dynamic | Dynamic | Static |
| Execution | Interpreted | Interpreted | Compiled |
| Platform | Browser/Server| Multi-purpose | JVM |
| Paradigms | Multi-paradigm| Multi-paradigm| OOP |
---
## 🔹 How JavaScript Runs?
1. Browser loads HTML/CSS
2. JavaScript engine (V8, SpiderMonkey) executes JS code
3. Can manipulate DOM (Document Object Model)
4. Handles user interactions
---
## 🔹 Setting Up JavaScript
### 1. In HTML File (Most Common)
### 2. Browser Console
- Press
- Type JS commands directly
### 3. Node.js (Server-Side)
---
## 🔹 Your First JavaScript Program
---
## 🔹 Variables & Data Types
JavaScript has 3 ways to declare variables:
### 1. Variable Declaration
### 2. Data Types
| Type | Example | Denoscription |
|-------------|--------------------------|--------------------------|
|
|
|
|
|
|
|
### 3. Type Checking
---
## 🔹 Operators
### 1. Arithmetic
### 2. Comparison
### 3. Logical
---
## 🔹 Type Conversion
### 1. Explicit Conversion
### 2. Implicit Conversion
---
## 🔹 Practical Example: Simple Calculator
---
#JavaScript #WebDev #Programming #BeginnerFriendly
Welcome to Part 1 of our comprehensive 10-part JavaScript series! This tutorial is designed for absolute beginners with detailed explanations and practical examples.
---
## 🔹 What is JavaScript?
JavaScript is a high-level, interpreted programming language that:
- Runs in web browsers (client-side)
- Can also run on servers (Node.js)
- Adds interactivity to websites
- Works with HTML/CSS to create dynamic web pages
Key Features:
✔️ Event-driven programming
✔️ Supports object-oriented and functional styles
✔️ Dynamically typed
✔️ Asynchronous operations (callbacks, promises)
---
## 🔹 JavaScript vs Other Languages
| Feature | JavaScript | Python | Java |
|---------------|---------------|---------------|---------------|
| Typing | Dynamic | Dynamic | Static |
| Execution | Interpreted | Interpreted | Compiled |
| Platform | Browser/Server| Multi-purpose | JVM |
| Paradigms | Multi-paradigm| Multi-paradigm| OOP |
---
## 🔹 How JavaScript Runs?
1. Browser loads HTML/CSS
2. JavaScript engine (V8, SpiderMonkey) executes JS code
3. Can manipulate DOM (Document Object Model)
4. Handles user interactions
HTML → Browser → JavaScript Engine → Execution
---
## 🔹 Setting Up JavaScript
### 1. In HTML File (Most Common)
<noscript>
// Your JavaScript code here
alert("Hello World!");
</noscript>
<!-- OR External File -->
<noscript src="noscript.js"></noscript>
### 2. Browser Console
- Press
F12 → Console tab- Type JS commands directly
### 3. Node.js (Server-Side)
node filename.js
---
## 🔹 Your First JavaScript Program
// Single line comment
/* Multi-line
comment */
// Print to console
console.log("Hello World!");
// Alert popup
alert("Welcome to JavaScript!");
// HTML output
document.write("<h1>Hello from JS!</h1>");
---
## 🔹 Variables & Data Types
JavaScript has 3 ways to declare variables:
### 1. Variable Declaration
let age = 25; // Mutable (block-scoped)
const PI = 3.14; // Immutable
var name = "Ali"; // Old way (function-scoped)
### 2. Data Types
| Type | Example | Denoscription |
|-------------|--------------------------|--------------------------|
|
Number | 42, 3.14 | All numbers ||
String | "Hello", 'World' | Text data ||
Boolean | true, false | Logical values ||
Object | {name: "Ali", age: 25} | Key-value pairs ||
Array | [1, 2, 3] | Ordered lists ||
Null | null | Intentional empty value ||
Undefined | undefined | Uninitialized variable |### 3. Type Checking
typeof "Hello"; // "string"
typeof 42; // "number"
typeof true; // "boolean"
typeof {}; // "object"
---
## 🔹 Operators
### 1. Arithmetic
let x = 10, y = 3;
console.log(x + y); // 13
console.log(x - y); // 7
console.log(x * y); // 30
console.log(x / y); // 3.333...
console.log(x % y); // 1 (modulus)
### 2. Comparison
console.log(5 == "5"); // true (loose equality)
console.log(5 === "5"); // false (strict equality)
console.log(5 != "5"); // false
console.log(5 !== "5"); // true
### 3. Logical
true && false; // AND → false
true || false; // OR → true
!true; // NOT → false
---
## 🔹 Type Conversion
### 1. Explicit Conversion
String(123); // "123"
Number("3.14"); // 3.14
Boolean(1); // true
### 2. Implicit Conversion
"5" + 2; // "52" (string concatenation)
"5" - 2; // 3 (numeric operation)
---
## 🔹 Practical Example: Simple Calculator
<noscript>
let num1 = parseFloat(prompt("Enter first number:"));
let num2 = parseFloat(prompt("Enter second number:"));
console.log(`Addition: ${num1 + num2}`);
console.log(`Subtraction: ${num1 - num2}`);
console.log(`Multiplication: ${num1 * num2}`);
console.log(`Division: ${num1 / num2}`);
</noscript>
---
## 🔹 Best Practices for Beginners
1. Use `const` by default,
2. Always declare variables before use
3. Use strict equality (`===`) instead of
4. Name variables meaningfully (e.g.,
5. Comment your code for complex logic
---
### 📌 What's Next?
In Part 2, we'll cover:
➡️ Conditionals (if/else, switch)
➡️ Loops (for, while)
➡️ Functions
#LearnJavaScript #CodingBasics #WebDevelopment 🚀
Practice Exercise:
1. Create variables for your name, age, and country
2. Calculate the area of a circle (PI * r²)
3. Try different type conversions
1. Use `const` by default,
let when needed, avoid var 2. Always declare variables before use
3. Use strict equality (`===`) instead of
== 4. Name variables meaningfully (e.g.,
userAge not x) 5. Comment your code for complex logic
---
### 📌 What's Next?
In Part 2, we'll cover:
➡️ Conditionals (if/else, switch)
➡️ Loops (for, while)
➡️ Functions
#LearnJavaScript #CodingBasics #WebDevelopment 🚀
Practice Exercise:
1. Create variables for your name, age, and country
2. Calculate the area of a circle (PI * r²)
3. Try different type conversions
❤3
# 📚 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 denoscriptive 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 denoscriptive 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 | Denoscription | 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 | Denoscription | 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 denoscriptive 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 denoscriptive 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 | Denoscription |
|-------|-------------|
|
|
|
|
|
|
|
---
## 🔹 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>
<noscript>My Page</noscript>
</head>
<body>
<h1 id="main-noscript">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 --> noscript
noscript --> 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 noscript = document.getElementById('main-noscript');
// 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)
noscript.textContent = 'New Title';
// HTML content (use carefully!)
noscript.innerHTML = '<em>New</em> Title';
// Attribute changes
noscript.setAttribute('class', 'highlight');
### 2. Styling Elements
// Direct style property access
noscript.style.color = 'blue';
noscript.style.fontSize = '2rem';
// Multiple styles at once
noscript.style.cssText = 'color: blue; font-size: 2rem;';
// Toggle classes
noscript.classList.add('highlight');
noscript.classList.remove('highlight');
noscript.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 | Denoscription |
|-------|-------------|
|
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://news.1rj.ru/str/+QHlfCJcO2lRjZWVl
You can join at this link! 👆👇
https://news.1rj.ru/str/+QHlfCJcO2lRjZWVl
Join our channel today for free! Tomorrow it will cost 500$!
https://news.1rj.ru/str/+QHlfCJcO2lRjZWVl
You can join at this link! 👆👇
https://news.1rj.ru/str/+QHlfCJcO2lRjZWVl
❤2
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).
❤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'…
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
<noscript type="module">
import { initApp } from './app.js';
initApp();
</noscript>
---
## 🔹 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(noscript) {
const header = document.createElement('header');
header.innerHTML = `<h1>${noscript}</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();---
❤2
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 noscript 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 noscript 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 Denoscriptors
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 Denoscriptors
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('js@example.com');
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