├── bonus └── method-chaining.js ├── class-file ├── 1-what-is-javascript.md ├── 2-javascript-fundamentals.md ├── note3 │ ├── part1.md │ ├── part2.md │ └── part3.md ├── notes1 │ ├── 1.strings.md │ ├── 12.more-on-javscript-oop.md │ ├── 2.objects.md │ ├── 3.arrays.md │ ├── 4.arithmetic-operations.md │ ├── 5.control-flow.md │ ├── 6.functions.md │ ├── 7.more-on-functions.md │ ├── 8.anonymous-functions.md │ └── 9.recursive-functions.md ├── notes2 │ ├── 10.more-on-objects.md │ ├── 11.oop-javascript-class.md │ ├── 12.Introduction-to-async.md │ └── 13.more-on-async.md └── notes3 │ └── 14.es6-features.md ├── index.html ├── js ├── array.js ├── class-example.md ├── class │ ├── class1.js │ ├── class2.js │ ├── encapsulation.js │ ├── inheritance.js │ ├── polymorphism.js │ ├── practice │ │ ├── employee.js │ │ └── product.js │ └── staticmethods.js ├── example1.js ├── main.js ├── objects.js └── strings.js ├── note2jsfiles ├── intro-to-asnyc.js └── intro-to-async2.js ├── note3jsfiles ├── file2.js ├── main.js ├── restparamters.js └── spreadoperator.js ├── note5jsfiles ├── authHelper.js ├── employeeChecks.js ├── main.js └── package.json ├── practice-sessions ├── practice1.js ├── practice2.js └── practice3.js └── readme.md /bonus/method-chaining.js: -------------------------------------------------------------------------------- 1 | class Calculator { 2 | constructor(value) { 3 | this.value = value 4 | } 5 | 6 | add(num) { 7 | this.value += num 8 | return this 9 | } 10 | 11 | subtract(num) { 12 | this.value -= num 13 | return this 14 | } 15 | 16 | multiply(num) { 17 | this.value *= num 18 | return this 19 | } 20 | 21 | divide(num) { 22 | this.value /= num 23 | return this 24 | } 25 | 26 | getResult() { 27 | return this.value 28 | } 29 | } 30 | 31 | const result = new Calculator(10) 32 | .add(5) 33 | .subtract(8) 34 | .multiply(2) 35 | .divide(2) 36 | .getResult() 37 | 38 | console.log(result) -------------------------------------------------------------------------------- /class-file/1-what-is-javascript.md: -------------------------------------------------------------------------------- 1 | # What is Javascript? 2 | 3 | JavaScript is a programming language that is primarily used for creating interactive and dynamic content on websites. It is an essential part of web development and allows you to add functionality, manipulate the content of a webpage, and respond to user actions. 4 | 5 | Here's a simple breakdown for newbies: 6 | 7 | 1. **What is JavaScript?** 8 | - JavaScript is a scripting language that enables you to make your website more interactive. 9 | - It runs on the client side, meaning it operates within your web browser. 10 | 11 | 2. ###### **What can you do with JavaScript?** 12 | 13 | - **Dynamic Content:** You can change the content of a webpage on the fly. For example, you can update text, images, or other elements without reloading the entire page. 14 | - **User Interaction:** JavaScript allows you to respond to user actions such as clicks, key presses, and mouse movements. 15 | - **Form Validation:** You can validate user inputs in forms before submitting them to ensure they meet certain criteria. 16 | - ###### **Animations:** You can create animations and transitions to enhance the visual experience of your website. 17 | 18 | 3. **How is JavaScript used?** 19 | - You embed JavaScript code directly into your HTML documents or link to external JavaScript files. 20 | - Example within HTML: 21 | ```html 22 | 26 | ``` 27 | - Example linking to an external JavaScript file: 28 | ```html 29 | 30 | ``` 31 | 32 | 4. **Basic Syntax:** 33 | - JavaScript code is written in plain text and follows a specific syntax. Here's a simple example: 34 | ```javascript 35 | // Declare a variable 36 | let greeting = "Hello, World!"; 37 | 38 | // Display an alert with the variable value 39 | alert(greeting); 40 | ``` 41 | 42 | 5. **Where does JavaScript run?** 43 | - JavaScript runs in the browser, meaning it is executed on the user's device. This is different from server-side languages like PHP or Python, which run on the web server. 44 | 45 | 6. **Frameworks and Libraries:** 46 | - JavaScript has many frameworks and libraries (e.g., React, Angular, Vue.js) that make it easier to build complex web applications by providing pre-built components and structures. 47 | -------------------------------------------------------------------------------- /class-file/2-javascript-fundamentals.md: -------------------------------------------------------------------------------- 1 | ### 1. **Syntax:** 2 | - **Definition:** Syntax refers to the set of rules that dictate how programs written in a language (in this case, JavaScript) should be structured. 3 | - **Example:** 4 | 5 | ```javascript 6 | // This is a comment 7 | let variableName = "Hello, World!"; // Variable assignment 8 | console.log(variableName); // Output to the console 9 | ``` 10 | 11 | ### 2. **Variables:** 12 | - **Definition:** Variables are containers for storing data values. They allow you to name and store values for later use. 13 | - **Example:** 14 | ```javascript 15 | let age = 25; // Declare and initialize a variable 16 | ``` 17 | 18 | ### 3. **Data Types:** 19 | - **Definition:** Data types specify the type of data that a variable can hold. JavaScript has several data types, including Number, String, Boolean, Object, and more. 20 | - **Example:** 21 | ```javascript 22 | let name = "John"; // String 23 | let age = 30; // Number 24 | let isStudent = true; // Boolean 25 | ``` 26 | 27 | ### 4. **Number:** 28 | - **Definition:** The Number data type represents both integers and floating-point numbers. 29 | - **Example:** 30 | ```javascript 31 | let num = 42; // Integer 32 | let pi = 3.14; // Floating-point number 33 | ``` 34 | 35 | ### 5. **Numeric Separator:** 36 | - **Definition:** Numeric separators allow you to make numeric literals more readable by adding underscores to separate groups of digits. 37 | - **Example:** 38 | ```javascript 39 | let billion = 1_000_000_000; // Numeric separator for better readability 40 | ``` 41 | 42 | ### 6. **Octal and Binary Literals:** 43 | - **Definition:** Octal literals are base-8 numbers (e.g., 0755), and binary literals are base-2 numbers (e.g., 0b1010). 44 | - **Example:** 45 | ```javascript 46 | let octalNum = 0o755; // Octal literal 47 | let binaryNum = 0b1010; // Binary literal 48 | ``` 49 | 50 | ### 7. **Boolean:** 51 | - **Definition:** Boolean represents true or false values. 52 | - **Example:** 53 | ```javascript 54 | let isTrue = true; 55 | let isFalse = false; 56 | ``` 57 | 58 | ### 8. **String:** 59 | - **Definition:** The String data type represents sequences of characters. 60 | - **Example:** 61 | ```javascript 62 | let greeting = "Hello, World!"; 63 | ``` 64 | 65 | ### 9. **Object:** 66 | - **Definition:** Objects are complex data types that can store multiple key-value pairs. 67 | - **Example:** 68 | ```javascript 69 | let person = { 70 | name: "John", 71 | age: 30, 72 | isStudent: false 73 | }; 74 | ``` 75 | 76 | ### 10. **Primitive vs. Reference Values:** 77 | - **Definition:** Primitive values (like numbers and strings) are stored directly in memory, while reference values (like objects and arrays) store references to the actual data in memory. 78 | - **Example:** 79 | ```javascript 80 | // Primitive value 81 | let x = 10; 82 | 83 | // Reference value 84 | let array = [1, 2, 3]; 85 | ``` 86 | 87 | ### 11. **Array:** 88 | - **Definition:** An array is a special variable that can hold multiple values in a single variable. 89 | - **Example:** 90 | ```javascript 91 | let fruits = ["apple", "orange", "banana"]; 92 | ``` 93 | -------------------------------------------------------------------------------- /class-file/note3/part1.md: -------------------------------------------------------------------------------- 1 | **1. Objects and Prototypes** 2 | 3 | In JavaScript, objects and prototypes are fundamental concepts that form the basis of Object-Oriented Programming (OOP). Understanding how objects and prototypes work is crucial for building robust and maintainable JavaScript applications. 4 | 5 | **Objects:** 6 | 7 | In JavaScript, an object is a collection of key-value pairs, where keys are strings (or symbols) and values can be of any data type, including other objects, functions, arrays, etc. Objects in JavaScript can be created using object literals, constructors, or classes (in ES6 and later). 8 | 9 | ```javascript 10 | // Object literal 11 | const person = { 12 | name: 'John', 13 | age: 30, 14 | greet() { 15 | console.log(`Hello, my name is ${this.name}`); 16 | } 17 | }; 18 | 19 | // Constructor function 20 | function Person(name, age) { 21 | this.name = name; 22 | this.age = age; 23 | } 24 | 25 | // Class (ES6) 26 | class Person { 27 | constructor(name, age) { 28 | this.name = name; 29 | this.age = age; 30 | } 31 | } 32 | ``` 33 | 34 | **Prototypes:** 35 | 36 | Prototypes are a mechanism in JavaScript that allows objects to inherit properties and methods from other objects. Every object in JavaScript has an internal prototype (referred to as `__proto__`) that it inherits properties and methods from. 37 | 38 | ```javascript 39 | // Using prototypes to add methods to objects 40 | function Person(name, age) { 41 | this.name = name; 42 | this.age = age; 43 | } 44 | 45 | Person.prototype.greet = function() { 46 | console.log(`Hello, my name is ${this.name}`); 47 | }; 48 | 49 | const john = new Person('John', 30); 50 | john.greet(); // Output: Hello, my name is John 51 | ``` 52 | 53 | Prototypes are used extensively in JavaScript to implement inheritance and share behavior among objects efficiently. 54 | 55 | **Benefits of Objects and Prototypes:** 56 | 57 | - **Code Reusability:** Objects and prototypes facilitate code reusability by allowing properties and methods to be shared among objects. 58 | - **Encapsulation:** Objects encapsulate related data and behavior, making the code more modular and easier to manage. 59 | - **Inheritance:** Prototypal inheritance allows objects to inherit properties and methods from other objects, enabling hierarchical relationships and code reuse. -------------------------------------------------------------------------------- /class-file/note3/part2.md: -------------------------------------------------------------------------------- 1 | **2. Constructors and Classes (ES6)** 2 | 3 | Constructors and classes in JavaScript provide syntactic sugar for creating objects and implementing object-oriented programming principles. They offer a more structured and intuitive way to define and instantiate objects. 4 | 5 | **Constructors:** 6 | 7 | In traditional JavaScript, constructors are functions used to create and initialize objects. They are invoked with the `new` keyword to create new instances of objects. 8 | 9 | ```javascript 10 | // Constructor function 11 | function Person(name, age) { 12 | this.name = name; 13 | this.age = age; 14 | } 15 | 16 | // Creating new instances 17 | const john = new Person('John', 30); 18 | const jane = new Person('Jane', 25); 19 | ``` 20 | 21 | Constructors can be thought of as blueprints for creating objects, where each instance inherits properties and methods defined within the constructor. 22 | 23 | **Classes (ES6):** 24 | 25 | ES6 introduced a class syntax that provides a more familiar and intuitive way to define constructors and implement inheritance in JavaScript. 26 | 27 | ```javascript 28 | // Class definition 29 | class Person { 30 | constructor(name, age) { 31 | this.name = name; 32 | this.age = age; 33 | } 34 | } 35 | 36 | // Creating new instances 37 | const john = new Person('John', 30); 38 | const jane = new Person('Jane', 25); 39 | ``` 40 | 41 | Under the hood, classes in JavaScript are still based on prototypes, providing a more concise and expressive way to work with objects. 42 | 43 | **Key Differences:** 44 | 45 | - **Syntax:** Classes provide a more concise and readable syntax for defining constructors and creating objects. 46 | - **Inheritance:** Classes support extends keyword for implementing inheritance, whereas constructors rely on prototype chaining for inheritance. 47 | 48 | **Benefits of Constructors and Classes:** 49 | 50 | - **Simplicity:** Constructors and classes offer a straightforward and intuitive way to define and instantiate objects. 51 | - **Encapsulation:** They encapsulate related data and behavior within objects, promoting code organization and modularity. 52 | - **Inheritance:** Classes support inheritance, allowing objects to inherit properties and methods from other objects, facilitating code reuse and extension. -------------------------------------------------------------------------------- /class-file/note3/part3.md: -------------------------------------------------------------------------------- 1 | **3. Object-Oriented Programming Principles** 2 | 3 | Object-Oriented Programming (OOP) principles provide guidelines for designing and structuring code in a way that promotes reusability, maintainability, and scalability. Let's explore these principles and their practical implementation in JavaScript. 4 | 5 | **1. Aggregation:** 6 | 7 | Aggregation represents a relationship where one object contains references to other objects, but the contained objects can exist independently of the container. It emphasizes the "has-a" relationship. 8 | 9 | **Practical Example:** 10 | 11 | Consider a Library class that aggregates Book objects: 12 | 13 | ```javascript 14 | class Book { 15 | constructor(title, author) { 16 | this.title = title; 17 | this.author = author; 18 | } 19 | } 20 | 21 | class Library { 22 | constructor() { 23 | this.books = []; // Aggregation 24 | } 25 | 26 | addBook(book) { 27 | this.books.push(book); 28 | } 29 | } 30 | 31 | const book1 = new Book('The Great Gatsby', 'F. Scott Fitzgerald'); 32 | const book2 = new Book('To Kill a Mockingbird', 'Harper Lee'); 33 | 34 | const library = new Library(); 35 | library.addBook(book1); 36 | library.addBook(book2); 37 | ``` 38 | 39 | **2. Composition:** 40 | 41 | Composition represents a relationship where one object contains another object as a part of its state. It emphasizes the "part-of" relationship. 42 | 43 | **Practical Example:** 44 | 45 | Consider a Car class composed of Engine and Wheels objects: 46 | 47 | ```javascript 48 | class Engine { 49 | start() { 50 | console.log('Engine started'); 51 | } 52 | } 53 | 54 | class Wheels { 55 | rotate() { 56 | console.log('Wheels rotating'); 57 | } 58 | } 59 | 60 | class Car { 61 | constructor() { 62 | this.engine = new Engine(); // Composition 63 | this.wheels = new Wheels(); // Composition 64 | } 65 | 66 | drive() { 67 | this.engine.start(); 68 | this.wheels.rotate(); 69 | console.log('Car driving'); 70 | } 71 | } 72 | 73 | const car = new Car(); 74 | car.drive(); 75 | ``` 76 | 77 | **3. Multiplicity:** 78 | 79 | Multiplicity represents the cardinality of relationships between objects, indicating how many instances of one class are associated with instances of another class. 80 | 81 | **Practical Example:** 82 | 83 | Consider a Classroom class that has multiple Student objects: 84 | 85 | ```javascript 86 | class Student { 87 | constructor(name, age) { 88 | this.name = name; 89 | this.age = age; 90 | } 91 | } 92 | 93 | class Classroom { 94 | constructor() { 95 | this.students = []; // Multiplicity 96 | } 97 | 98 | addStudent(student) { 99 | this.students.push(student); 100 | } 101 | } 102 | 103 | const student1 = new Student('Alice', 20); 104 | const student2 = new Student('Bob', 22); 105 | 106 | const classroom = new Classroom(); 107 | classroom.addStudent(student1); 108 | classroom.addStudent(student2); 109 | ``` 110 | 111 | **4. Inheritance:** 112 | 113 | Inheritance allows one class (subclass) to inherit properties and methods from another class (superclass), facilitating code reuse and promoting a hierarchical relationship. 114 | 115 | **Practical Example:** 116 | 117 | Consider a Parent class and a Child class inheriting from it: 118 | 119 | ```javascript 120 | class Parent { 121 | greet() { 122 | console.log('Hello from Parent'); 123 | } 124 | } 125 | 126 | class Child extends Parent { 127 | greet() { 128 | console.log('Hello from Child'); 129 | } 130 | } 131 | 132 | const parent = new Parent(); 133 | parent.greet(); // Output: Hello from Parent 134 | 135 | const child = new Child(); 136 | child.greet(); // Output: Hello from Child 137 | ``` 138 | 139 | **5. Encapsulation:** 140 | 141 | Encapsulation hides the internal state of an object and restricts direct access to it, promoting data integrity and reducing code complexity. 142 | 143 | **Practical Example:** 144 | 145 | Consider a BankAccount class with private balance: 146 | 147 | ```javascript 148 | class BankAccount { 149 | #balance = 0; // Encapsulation 150 | 151 | deposit(amount) { 152 | this.#balance += amount; 153 | } 154 | 155 | withdraw(amount) { 156 | if (this.#balance >= amount) { 157 | this.#balance -= amount; 158 | } else { 159 | console.log('Insufficient funds'); 160 | } 161 | } 162 | 163 | getBalance() { 164 | return this.#balance; 165 | } 166 | } 167 | 168 | const account = new BankAccount(); 169 | account.deposit(100); 170 | console.log(account.getBalance()); // Output: 100 171 | account.withdraw(50); 172 | console.log(account.getBalance()); // Output: 50 173 | ``` 174 | 175 | **6. Polymorphism:** 176 | 177 | Polymorphism allows objects of different classes to be treated as objects of a common superclass, enabling flexibility and extensibility in code. 178 | 179 | **Practical Example:** 180 | 181 | Consider a Shape superclass and Rectangle and Circle subclasses: 182 | 183 | ```javascript 184 | class Shape { 185 | area() { 186 | return 0; 187 | } 188 | } 189 | 190 | class Rectangle extends Shape { 191 | constructor(width, height) { 192 | super(); 193 | this.width = width; 194 | this.height = height; 195 | } 196 | 197 | area() { 198 | return this.width * this.height; 199 | } 200 | } 201 | 202 | class Circle extends Shape { 203 | constructor(radius) { 204 | super(); 205 | this.radius = radius; 206 | } 207 | 208 | area() { 209 | return Math.PI * this.radius * this.radius; 210 | } 211 | } 212 | 213 | const rectangle = new Rectangle(5, 10); 214 | console.log(rectangle.area()); // Output: 50 215 | 216 | const circle = new Circle(5); 217 | console.log(circle.area()); // Output: ~78.54 218 | ``` 219 | -------------------------------------------------------------------------------- /class-file/notes1/1.strings.md: -------------------------------------------------------------------------------- 1 | 1. **String Creation:** 2 | JavaScript strings can be created using single quotes (`'`), double quotes (`"`), or template literals (`` ` ``). Let's explore each method: 3 | 4 | ```javascript 5 | // Single quotes 6 | let strSingle = 'Hello'; 7 | 8 | // Double quotes 9 | let strDouble = "World"; 10 | 11 | // Template literals 12 | let templateStr = `JavaScript is ${strSingle} ${strDouble}!`; 13 | ``` 14 | 15 | Template literals, introduced in ES6, allow for dynamic string creation with embedded expressions, enhancing readability and flexibility. 16 | 17 | 2. **String Immutability:** 18 | JavaScript strings are immutable, meaning that once created, their content cannot be changed. Any operation that seems to modify a string actually creates a new string. 19 | 20 | ```javascript 21 | let originalStr = 'Immutable'; 22 | let modifiedStr = originalStr.toUpperCase(); 23 | 24 | console.log(originalStr); // Output: Immutable 25 | console.log(modifiedStr); // Output: IMMUTABLE 26 | ``` 27 | 28 | 3. **Template Literals and Interpolation:** 29 | Template literals support string interpolation, enabling the inclusion of variables and expressions directly within a string. 30 | 31 | ```javascript 32 | let name = 'John'; 33 | let message = `Hi, I'm ${name}.`; 34 | 35 | console.log(message); // Output: Hi, I'm John. 36 | ``` 37 | 38 | 4. **Escaping Special Characters:** 39 | To include special characters in a string, you can use the backslash (`\`) for escaping. 40 | 41 | ```javascript 42 | let specialStr = 'I\'m a string with a single quote!'; 43 | ``` 44 | 45 | 5. **String Length:** 46 | The `length` property is used to determine the number of characters in a string. 47 | 48 | ```javascript 49 | let greeting = "Good Morning!"; 50 | console.log(greeting.length); // Output: 13 51 | ``` 52 | 53 | 6. **Accessing Characters:** 54 | Strings can be treated as arrays, allowing you to access individual characters using zero-based indexing. 55 | 56 | ```javascript 57 | let str = "Hello"; 58 | console.log(str[0]); // Output: "H" 59 | console.log(str[str.length - 1]); // Output: "o" 60 | ``` 61 | 62 | 7. **String Concatenation:** 63 | Strings can be concatenated using the `+` operator or the `+=` operator for incremental concatenation. 64 | 65 | ```javascript 66 | let firstName = 'John'; 67 | let greeting = 'Hello ' + firstName; 68 | 69 | console.log(greeting); // Output: Hello John 70 | ``` 71 | 72 | ```javascript 73 | let className = 'btn'; 74 | className += ' btn-primary'; 75 | className += ' none'; 76 | 77 | console.log(className); // Output: btn btn-primary none 78 | ``` 79 | 80 | 8. **Converting Values to Strings:** 81 | Various methods, including `String()`, `"" + n`, and `n.toString()`, can be used to convert non-string values to strings. 82 | 83 | ```javascript 84 | let number = 42; 85 | let strNumber = String(number); 86 | ``` 87 | 88 | 9. **Comparing Strings:** 89 | String comparison is performed using operators such as `>`, `>=`, `<`, `<=`, and `==`. It's important to note that comparisons are based on the numeric values of characters. 90 | 91 | ```javascript 92 | let result = 'a' < 'b'; // true 93 | ``` 94 | 95 | ```javascript 96 | let result = 'a' < 'B'; // false 97 | ``` -------------------------------------------------------------------------------- /class-file/notes1/12.more-on-javscript-oop.md: -------------------------------------------------------------------------------- 1 | # Advanced Object-Oriented Programming Features in JavaScript 2 | 3 | These features include class expressions, computed properties, getters and setters, inheritance, `new.target`, static methods, static properties, private fields, private methods, and the `instanceof` operator. 4 | 5 | ## 1. Class Expressions 6 | 7 | Class expressions allow you to define a class without a class name. They can be named or unnamed. 8 | 9 | ```javascript 10 | // Named class expression 11 | let Rectangle = class RectangleClass { 12 | constructor(width, height) { 13 | this.width = width; 14 | this.height = height; 15 | } 16 | }; 17 | 18 | // Unnamed class expression 19 | let Circle = class { 20 | constructor(radius) { 21 | this.radius = radius; 22 | } 23 | }; 24 | ``` 25 | 26 | ## 2. Getters & Setters 27 | 28 | Getters and setters provide a way to control access to the properties of an object. 29 | 30 | ```javascript 31 | class Square { 32 | constructor(side) { 33 | this._side = side; 34 | } 35 | 36 | get side() { 37 | return this._side; 38 | } 39 | 40 | set side(value) { 41 | if (value > 0) { 42 | this._side = value; 43 | } else { 44 | console.error('Side must be greater than 0.'); 45 | } 46 | } 47 | } 48 | 49 | let mySquare = new Square(5); 50 | console.log(mySquare.side); // Using the getter 51 | mySquare.side = 10; // Using the setter 52 | ``` 53 | 54 | ## 3. Computed Properties 55 | 56 | Computed properties allow you to define object properties with dynamic names. 57 | 58 | ```javascript 59 | let propertyName = 'color'; 60 | 61 | let myObject = { 62 | [propertyName]: 'blue', 63 | [1 + 2]: 'three' 64 | }; 65 | 66 | console.log(myObject.color); // 'blue' 67 | console.log(myObject[3]); // 'three' 68 | ``` 69 | 70 | ## 4. Inheritance 71 | 72 | Inheritance allows a class to inherit properties and methods from another class. 73 | 74 | ```javascript 75 | class Animal { 76 | constructor(name) { 77 | this.name = name; 78 | } 79 | 80 | speak() { 81 | console.log(`${this.name} makes a sound.`); 82 | } 83 | } 84 | 85 | class Dog extends Animal { 86 | speak() { 87 | console.log(`${this.name} barks.`); 88 | } 89 | } 90 | 91 | let myDog = new Dog('Buddy'); 92 | myDog.speak(); // 'Buddy barks.' 93 | ``` 94 | 95 | ## 5. `new.target` 96 | 97 | The `new.target` property refers to the constructor or function that was directly invoked with the `new` keyword. 98 | 99 | ```javascript 100 | function Example() { 101 | if (new.target === Example) { 102 | console.log('Constructor was called with new keyword.'); 103 | } else { 104 | console.log('Constructor was called without new keyword.'); 105 | } 106 | } 107 | 108 | let instance = new Example(); // 'Constructor was called with new keyword.' 109 | let withoutNew = Example(); // 'Constructor was called without new keyword.' 110 | ``` 111 | 112 | ## 6. Static Methods 113 | 114 | Static methods are associated with the class itself, not with instances of the class. 115 | 116 | ```javascript 117 | class MathUtils { 118 | static add(a, b) { 119 | return a + b; 120 | } 121 | } 122 | 123 | console.log(MathUtils.add(2, 3)); // 5 124 | ``` 125 | 126 | ## 7. Static Properties 127 | 128 | Static properties are shared among all instances of a class and are accessed directly on the class. 129 | 130 | ```javascript 131 | class Circle { 132 | static pi = 3.14; 133 | } 134 | 135 | console.log(Circle.pi); // 3.14 136 | ``` 137 | 138 | ## 8. Private Fields 139 | 140 | Private fields are not accessible from outside the class. 141 | 142 | ```javascript 143 | class Counter { 144 | #count = 0; // private field 145 | 146 | increment() { 147 | this.#count++; 148 | } 149 | 150 | getCount() { 151 | this.increment(); 152 | return this.#count; 153 | } 154 | } 155 | 156 | let myCounter = new Counter(); 157 | console.log(myCounter.getCount()); 158 | ``` 159 | 160 | ## 9. Private Methods 161 | 162 | Private methods are not accessible from outside the class. 163 | 164 | ```javascript 165 | class Validator { 166 | #validateEmail(email) { 167 | // Validation logic 168 | return email.includes('@'); 169 | } 170 | 171 | isValidEmail(email) { 172 | return this.#validateEmail(email); 173 | } 174 | } 175 | 176 | let validator = new Validator(); 177 | console.log(validator.isValidEmail('example@example.com')); 178 | ``` 179 | 180 | ## 10. `instanceof` Operator 181 | 182 | The `instanceof` operator checks if an object is an instance of a particular class. 183 | 184 | ```javascript 185 | let myDog = new Dog('Buddy'); 186 | console.log(myDog instanceof Animal); // true 187 | ``` -------------------------------------------------------------------------------- /class-file/notes1/2.objects.md: -------------------------------------------------------------------------------- 1 | 1. **Object Creation:** 2 | In JavaScript, an object is an unordered collection of key-value pairs, with each pair referred to as a property. Properties can have various values, including strings, numbers, arrays, and even functions. The object literal notation is the most commonly used method for creating objects: 3 | 4 | ```javascript 5 | // Creating an empty object 6 | let empty = {}; 7 | 8 | // Creating an object with properties 9 | let person = { 10 | firstName: 'John', 11 | lastName: 'Doe' 12 | }; 13 | ``` 14 | 15 | 2. **Accessing Properties:** 16 | Objects provide two primary notations for accessing properties – the dot notation (.) and the array-like notation ([]). 17 | 18 | ```javascript 19 | // Dot notation 20 | console.log(person.firstName); // Output: John 21 | 22 | // Array-like notation 23 | console.log(person['lastName']); // Output: Doe 24 | ``` 25 | 26 | It's important to note that array-like notation is essential when dealing with property names containing spaces. 27 | 28 | 3. **Modifying and Adding Properties:** 29 | To modify the value of an existing property, use the assignment operator. New properties can be added to an object even after its creation: 30 | 31 | ```javascript 32 | // Modifying a property 33 | person.firstName = 'Jane'; 34 | 35 | // Adding a new property 36 | person.age = 25; 37 | ``` 38 | 39 | 4. **Deleting Properties:** 40 | The `delete` operator allows you to remove a property from an object: 41 | 42 | ```javascript 43 | // Deleting a property 44 | delete person.age; 45 | ``` 46 | 47 | Be cautious when using `delete`, as attempting to access a deleted property will result in `undefined`. 48 | 49 | 5. **Checking Property Existence:** 50 | The `in` operator is used to check if a property exists in an object: 51 | 52 | ```javascript 53 | // Checking property existence 54 | console.log('ssn' in employee); // Output: false 55 | console.log('employeeId' in employee); // Output: true 56 | ``` 57 | 58 | This is useful for conditional checks before accessing properties. -------------------------------------------------------------------------------- /class-file/notes1/3.arrays.md: -------------------------------------------------------------------------------- 1 | 1. **Array Characteristics:** 2 | JavaScript arrays have distinct features: 3 | - They can hold values of mixed types, including numbers, strings, booleans, and null. 4 | - The size of an array is dynamic and auto-growing, eliminating the need to specify the size upfront. 5 | 6 | 2. **Creating JavaScript Arrays:** 7 | There are two primary ways to create arrays in JavaScript: 8 | 9 | - Using the `Array` constructor: 10 | ```javascript 11 | let scores = new Array(); 12 | ``` 13 | 14 | - Using array literal notation: 15 | ```javascript 16 | let colors = ['red', 'green', 'blue']; 17 | ``` 18 | 19 | The latter, array literal notation, is the preferred and more commonly used method. 20 | 21 | 3. **Accessing Array Elements:** 22 | Arrays in JavaScript are zero-based indexed, meaning the first element has an index of 0, the second has an index of 1, and so on. Accessing array elements can be done using square brackets with the index: 23 | 24 | ```javascript 25 | let mountains = ['Everest', 'Fuji', 'Nanga Parbat']; 26 | console.log(mountains[0]); // 'Everest' 27 | ``` 28 | 29 | To modify an element, assign the new value to the desired index. 30 | 31 | 4. **Getting the Array Size:** 32 | The `length` property of an array returns the number of elements: 33 | 34 | ```javascript 35 | let mountains = ['Everest', 'Fuji', 'Nanga Parbat']; 36 | console.log(mountains.length); // 3 37 | ``` 38 | 39 | 5. **Basic Operations on Arrays:** 40 | a) Adding an element to the end of an array using `push()`: 41 | ```javascript 42 | seas.push('Red Sea'); 43 | ``` 44 | 45 | b) Adding an element to the beginning of an array using `unshift()`: 46 | ```javascript 47 | seas.unshift('Red Sea'); 48 | ``` 49 | 50 | c) Removing an element from the end of an array using `pop()`: 51 | ```javascript 52 | const lastElement = seas.pop(); 53 | ``` 54 | 55 | d) Removing an element from the beginning of an array using `shift()`: 56 | ```javascript 57 | const firstElement = seas.shift(); 58 | ``` 59 | 60 | e) Finding the index of an element using `indexOf()`: 61 | ```javascript 62 | let index = seas.indexOf('North Sea'); 63 | ``` 64 | 65 | f) Checking if a value is an array using `Array.isArray()`: 66 | ```javascript 67 | console.log(Array.isArray(seas)); // true 68 | ``` -------------------------------------------------------------------------------- /class-file/notes1/4.arithmetic-operations.md: -------------------------------------------------------------------------------- 1 | ## 1. Arithmetic Operators: 2 | JavaScript supports standard arithmetic operators for basic mathematical operations. 3 | 4 | ```javascript 5 | let a = 5; 6 | let b = 2; 7 | 8 | let sum = a + b; // Addition 9 | let difference = a - b; // Subtraction 10 | let product = a * b; // Multiplication 11 | let quotient = a / b; // Division 12 | let remainder = a % b; // Remainder 13 | let exponentiation = a ** b; // Exponentiation 14 | ``` 15 | 16 | ## 2. Remainder Operator: 17 | The remainder operator (`%`) returns the remainder of a division operation. 18 | 19 | ```javascript 20 | let remainder = 10 % 3; // Result: 1 21 | ``` 22 | 23 | ## 3. Assignment Operators: 24 | Assignment operators are used to assign values to variables. 25 | 26 | ```javascript 27 | let x = 5; 28 | 29 | x += 3; // Equivalent to x = x + 3 30 | x -= 2; // Equivalent to x = x - 2 31 | x *= 4; // Equivalent to x = x * 4 32 | x /= 2; // Equivalent to x = x / 2 33 | ``` 34 | 35 | ## 4. Unary Operators: 36 | Unary operators operate on a single operand. 37 | 38 | ```javascript 39 | let num = 10; 40 | 41 | num++; // Increment by 1 42 | num--; // Decrement by 1 43 | let negation = -num; // Negation 44 | ``` 45 | 46 | ## 5. Comparison Operators: 47 | Comparison operators are used to compare values. 48 | 49 | ```javascript 50 | let a = 5; 51 | let b = 8; 52 | 53 | console.log(a > b); // Greater than 54 | console.log(a < b); // Less than 55 | console.log(a >= b); // Greater than or equal to 56 | console.log(a <= b); // Less than or equal to 57 | console.log(a === b); // Equal to (strict) 58 | console.log(a !== b); // Not equal to (strict) 59 | ``` 60 | 61 | ## 6. Logical Operators: 62 | Logical operators are used to combine or modify logical values. 63 | 64 | ```javascript 65 | let isTrue = true; 66 | let isFalse = false; 67 | 68 | console.log(isTrue && isFalse); // Logical AND 69 | console.log(isTrue || isFalse); // Logical OR 70 | console.log(!isTrue); // Logical NOT 71 | ``` 72 | 73 | ## 7. Logical Assignment Operators: 74 | Logical assignment operators combine logical operations with assignment. 75 | 76 | ```javascript 77 | let x = 5; 78 | 79 | x &&= 3; // Equivalent to x = x && 3 80 | x ||= 8; // Equivalent to x = x || 8 81 | ``` 82 | 83 | ## 8. Nullish Coalescing Operator: 84 | The nullish coalescing operator (`??`) returns the right-hand operand when the left-hand operand is null or undefined. 85 | 86 | ```javascript 87 | let x = null; 88 | let y = 5; 89 | 90 | let result = x ?? y; // Result: 5 91 | ``` 92 | 93 | ## 9. Exponentiation Operator: 94 | The exponentiation operator (`**`) raises the left operand to the power of the right operand. 95 | 96 | ```javascript 97 | let base = 2; 98 | let exponent = 3; 99 | 100 | let result = base ** exponent; // Result: 8 101 | ``` -------------------------------------------------------------------------------- /class-file/notes1/5.control-flow.md: -------------------------------------------------------------------------------- 1 | ## 1. `if` Statement: 2 | The `if` statement allows you to execute a block of code if a specified condition is true. 3 | 4 | ```javascript 5 | let condition = true; 6 | 7 | if (condition) { 8 | // Code to execute if the condition is true 9 | } 10 | ``` 11 | 12 | ## 2. `if-else` Statement: 13 | The `if-else` statement extends the `if` statement, providing an alternative block of code to execute if the condition is false. 14 | 15 | ```javascript 16 | let condition = false; 17 | 18 | if (condition) { 19 | // Code to execute if the condition is true 20 | } else { 21 | // Code to execute if the condition is false 22 | } 23 | ``` 24 | 25 | ## 3. `if-else if` Statement: 26 | The `if-else if` statement allows you to check multiple conditions in a sequential manner. 27 | 28 | ```javascript 29 | let score = 75; 30 | 31 | if (score >= 90) { 32 | // Code for excellent grade 33 | } else if (score >= 70) { 34 | // Code for good grade 35 | } else { 36 | // Code for other grades 37 | } 38 | ``` 39 | 40 | ## 4. Ternary Operator (`?:`): 41 | The ternary operator is a concise way to write an `if-else` statement in a single line. 42 | 43 | ```javascript 44 | let isRaining = true; 45 | 46 | let weather = isRaining ? 'Bring an umbrella' : 'Enjoy the sunshine'; 47 | ``` 48 | 49 | ## 5. `switch` Case: 50 | The `switch` statement is useful for handling multiple cases based on the value of an expression. 51 | 52 | ```javascript 53 | let day = 'Monday'; 54 | 55 | switch (day) { 56 | case 'Monday': 57 | console.log('It\'s the start of the week.'); 58 | break; 59 | case 'Friday': 60 | console.log('Weekend is almost here!'); 61 | break; 62 | default: 63 | console.log('It\'s a regular day.'); 64 | } 65 | ``` 66 | 67 | ## 6. `while` Loop: 68 | The `while` loop executes a block of code as long as the specified condition is true. 69 | 70 | ```javascript 71 | let count = 0; 72 | 73 | while (count < 5) { 74 | console.log('Count:', count); 75 | count++; 76 | } 77 | ``` 78 | 79 | ## 7. `do-while` Loop: 80 | The `do-while` loop is similar to the `while` loop but ensures that the block of code is executed at least once before checking the condition. 81 | 82 | ```javascript 83 | let i = 0; 84 | 85 | do { 86 | console.log('Index:', i); 87 | i++; 88 | } while (i < 5); 89 | ``` 90 | 91 | ## 8. `for` Loop: 92 | The `for` loop is a versatile loop structure with initialization, condition, and iteration components. 93 | 94 | ```javascript 95 | for (let i = 0; i < 5; i++) { 96 | console.log('Iteration:', i); 97 | } 98 | ``` 99 | 100 | ## 9. `break` Statement: 101 | The `break` statement is used to exit a loop prematurely. 102 | 103 | ```javascript 104 | for (let i = 0; i < 10; i++) { 105 | if (i === 5) { 106 | break; 107 | } 108 | console.log('Value:', i); 109 | } 110 | ``` 111 | 112 | ## 10. `continue` Statement: 113 | The `continue` statement skips the rest of the loop's code and continues to the next iteration. 114 | 115 | ```javascript 116 | for (let i = 0; i < 5; i++) { 117 | if (i === 2) { 118 | continue; 119 | } 120 | console.log('Value:', i); 121 | } 122 | ``` 123 | 124 | ## 11. Comma Operator: 125 | The comma operator allows you to execute multiple expressions within a single statement. 126 | 127 | ```javascript 128 | let a = 1, b = 2, c = 3; 129 | 130 | console.log(a, b, c); // Output: 1 2 3 131 | ``` -------------------------------------------------------------------------------- /class-file/notes1/6.functions.md: -------------------------------------------------------------------------------- 1 | ## 1. Functions: 2 | Functions in JavaScript are reusable blocks of code that can be defined and invoked. They enhance code organization and promote reusability. 3 | 4 | ### Declaration: 5 | ```javascript 6 | function greet(name) { 7 | console.log(`Hello, ${name}!`); 8 | } 9 | 10 | // Function Invocation 11 | greet('John'); // Output: Hello, John! 12 | ``` 13 | 14 | ## 2. Functions are First-Class Citizens: 15 | In JavaScript, functions are first-class citizens, meaning they can be treated like any other variable – assigned to variables, passed as arguments, and returned from other functions. 16 | 17 | ### Assignment to a Variable: 18 | ```javascript 19 | const sayHello = function(name) { 20 | console.log(`Hello, ${name}!`); 21 | }; 22 | 23 | sayHello('Alice'); // Output: Hello, Alice! 24 | ``` 25 | 26 | ### Passed as Arguments: 27 | ```javascript 28 | function executeFunction(fn, value) { 29 | fn(value); 30 | } 31 | 32 | executeFunction(sayHello, 'Bob'); // Output: Hello, Bob! 33 | ``` 34 | 35 | ### Returned from a Function: 36 | ```javascript 37 | function createGreetingFunction() { 38 | return function(name) { 39 | console.log(`Greetings, ${name}!`); 40 | }; 41 | } 42 | 43 | const greetFunction = createGreetingFunction(); 44 | greetFunction('Eve'); // Output: Greetings, Eve! 45 | ``` 46 | 47 | ## 3. Anonymous Functions: 48 | Anonymous functions are functions without a name. They are often used as arguments to other functions or within function expressions. 49 | 50 | ### Anonymous Function as an Argument: 51 | ```javascript 52 | setTimeout(function() { 53 | console.log('Delayed log.'); 54 | }, 1000); 55 | ``` 56 | 57 | ## 4. Understanding Pass-By-Value in JavaScript: 58 | In JavaScript, arguments are passed to functions by value. Understanding this concept is crucial for working with functions effectively. 59 | 60 | ```javascript 61 | function modifyValue(value) { 62 | value = 10; 63 | } 64 | 65 | let num = 5; 66 | modifyValue(num); 67 | console.log(num); // Output: 5 (unchanged) 68 | ``` 69 | 70 | ## 5. Recursive Functions: 71 | Recursive functions are functions that call themselves. They are useful for solving problems that can be broken down into smaller, similar sub-problems. 72 | 73 | ```javascript 74 | function factorial(n) { 75 | if (n <= 1) { 76 | return 1; 77 | } 78 | return n * factorial(n - 1); 79 | } 80 | 81 | console.log(factorial(5)); // Output: 120 82 | ``` 83 | 84 | ## 6. Default Parameters: 85 | JavaScript allows you to set default values for function parameters. If an argument is not provided during the function call, the default value is used. 86 | 87 | ```javascript 88 | function greet(name = 'Guest') { 89 | console.log(`Hello, ${name}!`); 90 | } 91 | 92 | greet(); // Output: Hello, Guest! 93 | greet('Sophia'); // Output: Hello, Sophia! 94 | ``` -------------------------------------------------------------------------------- /class-file/notes1/7.more-on-functions.md: -------------------------------------------------------------------------------- 1 | ### 1. Basic Function Definition and Invocation: 2 | 3 | ```javascript 4 | // Function definition 5 | function greet(name) { 6 | console.log('Hello, ' + name + '!'); 7 | } 8 | 9 | // Function invocation 10 | greet('Alice'); // Output: Hello, Alice! 11 | ``` 12 | 13 | ### 2. Function with Return Value: 14 | 15 | ```javascript 16 | // Function definition 17 | function addNumbers(a, b) { 18 | return a + b; 19 | } 20 | 21 | // Function invocation 22 | const sum = addNumbers(3, 7); 23 | console.log('Sum:', sum); // Output: Sum: 10 24 | ``` 25 | 26 | ### 3. Function with Multiple Parameters: 27 | 28 | ```javascript 29 | // Function definition 30 | function multiply(a, b, c) { 31 | return a * b * c; 32 | } 33 | 34 | // Function invocation 35 | const result = multiply(2, 3, 4); 36 | console.log('Result:', result); // Output: Result: 24 37 | ``` 38 | 39 | ### 4. Function with No Parameters: 40 | 41 | ```javascript 42 | // Function definition 43 | function greet() { 44 | console.log('Hello, there!'); 45 | } 46 | 47 | // Function invocation 48 | greet(); // Output: Hello, there! 49 | ``` 50 | 51 | ### 5. Function with Default Parameter: 52 | 53 | ```javascript 54 | // Function definition with default parameter 55 | function greet(name = 'Guest') { 56 | console.log('Hello, ' + name + '!'); 57 | } 58 | 59 | // Function invocation without argument 60 | greet(); // Output: Hello, Guest! 61 | 62 | // Function invocation with argument 63 | greet('Bob'); // Output: Hello, Bob! 64 | ``` 65 | 66 | ### 6. Function with Local Variables: 67 | 68 | ```javascript 69 | // Function definition 70 | function calculate() { 71 | let x = 5; 72 | let y = 3; 73 | let result = x * y; 74 | console.log('Result:', result); 75 | } 76 | 77 | // Function invocation 78 | calculate(); // Output: Result: 15 79 | ``` 80 | 81 | ### 7. Function with Global Variables: 82 | 83 | ```javascript 84 | // Global variable 85 | let globalVar = 'I am global'; 86 | 87 | // Function definition using global variable 88 | function displayGlobal() { 89 | console.log(globalVar); 90 | } 91 | 92 | // Function invocation 93 | displayGlobal(); // Output: I am global 94 | ``` 95 | 96 | ### 8. Function Expression: 97 | 98 | ```javascript 99 | // Function expression 100 | const subtract = function (a, b) { 101 | return a - b; 102 | }; 103 | 104 | // Function invocation 105 | const difference = subtract(8, 3); 106 | console.log('Difference:', difference); // Output: Difference: 5 107 | ``` 108 | 109 | ### 9. Arrow Function: 110 | 111 | ```javascript 112 | // Arrow function 113 | const square = (num) => num ** 2; 114 | 115 | // Function invocation 116 | const squaredValue = square(4); 117 | console.log('Squared Value:', squaredValue); // Output: Squared Value: 16 118 | ``` -------------------------------------------------------------------------------- /class-file/notes1/8.anonymous-functions.md: -------------------------------------------------------------------------------- 1 | ### 1. Anonymous Function as a Function Expression: 2 | 3 | ```javascript 4 | const addNumbers = function (a, b) { 5 | return a + b; 6 | }; 7 | 8 | console.log(addNumbers(3, 7)); // Output: 10 9 | ``` 10 | 11 | ### 2. Anonymous Function as an Argument to `map`: 12 | 13 | ```javascript 14 | const numbers = [1, 2, 3, 4]; 15 | 16 | const squaredNumbers = numbers.map(function (num) { 17 | return num ** 2; 18 | }); 19 | 20 | console.log(squaredNumbers); // Output: [1, 4, 9, 16] 21 | ``` 22 | 23 | ### 3. Anonymous Function in an Event Handler: 24 | 25 | ```javascript 26 | const button = document.getElementById('myButton'); 27 | 28 | button.addEventListener('click', function () { 29 | console.log('Button clicked!'); 30 | }); 31 | ``` 32 | 33 | ### 4. Anonymous Function in a setTimeout: 34 | 35 | ```javascript 36 | setTimeout(function () { 37 | console.log('Delayed log after 2 seconds.'); 38 | }, 2000); 39 | ``` 40 | 41 | ### 5. Anonymous Function in Array Filtering: 42 | 43 | ```javascript 44 | const numbers = [1, 5, 8, 10, 15]; 45 | 46 | const evenNumbers = numbers.filter(function (num) { 47 | return num % 2 === 0; 48 | }); 49 | 50 | console.log(evenNumbers); // Output: [8, 10] 51 | ``` 52 | 53 | ### 6. Anonymous Function in Immediate Invocation (IIFE): 54 | 55 | ```javascript 56 | (function () { 57 | console.log('This is an IIFE!'); 58 | })(); 59 | ``` 60 | 61 | ### 7. Anonymous Function as a Callback: 62 | 63 | ```javascript 64 | function performOperation(a, b, callback) { 65 | const result = callback(a, b); 66 | console.log('Result:', result); 67 | } 68 | 69 | performOperation(4, 6, function (x, y) { 70 | return x * y; 71 | }); // Output: Result: 24 72 | ``` 73 | 74 | ### 8. Anonymous Function in Promises: 75 | 76 | ```javascript 77 | const promise = new Promise(function (resolve, reject) { 78 | const success = true; 79 | 80 | if (success) { 81 | resolve('Promise resolved!'); 82 | } else { 83 | reject('Promise rejected!'); 84 | } 85 | }); 86 | 87 | promise.then(function (message) { 88 | console.log(message); 89 | }).catch(function (error) { 90 | console.error(error); 91 | }); 92 | ``` -------------------------------------------------------------------------------- /class-file/notes1/9.recursive-functions.md: -------------------------------------------------------------------------------- 1 | ### 1. Factorial Calculation: 2 | 3 | ```javascript 4 | function factorial(n) { 5 | // Base case: factorial of 0 or 1 is 1 6 | if (n <= 1) { 7 | return 1; 8 | } 9 | // Recursive case: n! = n * (n-1)! 10 | return n * factorial(n - 1); 11 | } 12 | 13 | console.log(factorial(5)); // Output: 120 14 | ``` 15 | 16 | In this example, the `factorial` function calculates the factorial of a number using recursion. The base case checks if `n` is 0 or 1, in which case the result is 1. Otherwise, it recursively calls itself with `n - 1` until reaching the base case. 17 | 18 | ### 2. Fibonacci Sequence: 19 | 20 | ```javascript 21 | function fibonacci(n) { 22 | // Base case: fibonacci of 0 or 1 is the number itself 23 | if (n <= 1) { 24 | return n; 25 | } 26 | // Recursive case: fib(n) = fib(n-1) + fib(n-2) 27 | return fibonacci(n - 1) + fibonacci(n - 2); 28 | } 29 | 30 | console.log(fibonacci(6)); // Output: 8 31 | ``` 32 | 33 | The `fibonacci` function calculates the nth Fibonacci number using recursion. The base case returns `n` for 0 and 1. The recursive case sums the two previous Fibonacci numbers (calculated by calling itself with `n - 1` and `n - 2`). 34 | 35 | ### 3. Countdown: 36 | 37 | ```javascript 38 | function countdown(n) { 39 | // Base case: stop when n is 0 40 | if (n <= 0) { 41 | console.log('Countdown complete!'); 42 | } else { 43 | console.log(n); 44 | // Recursive case: countdown with n-1 45 | countdown(n - 1); 46 | } 47 | } 48 | 49 | countdown(5); 50 | ``` 51 | 52 | In this example, the `countdown` function recursively counts down from a given number to 1. The base case stops the recursion when `n` is 0, and otherwise, it prints the current value of `n` and calls itself with `n - 1`. 53 | 54 | ### 4. Sum of Natural Numbers: 55 | 56 | ```javascript 57 | function sumOfNaturals(n) { 58 | // Base case: sum of first natural number is 1 59 | if (n === 1) { 60 | return 1; 61 | } 62 | // Recursive case: sum(n) = n + sum(n-1) 63 | return n + sumOfNaturals(n - 1); 64 | } 65 | 66 | console.log(sumOfNaturals(4)); // Output: 10 67 | ``` 68 | 69 | The `sumOfNaturals` function calculates the sum of the first `n` natural numbers using recursion. The base case returns 1 for `n` equal to 1. The recursive case sums `n` with the sum of the previous natural numbers (calculated by calling itself with `n - 1`). -------------------------------------------------------------------------------- /class-file/notes2/10.more-on-objects.md: -------------------------------------------------------------------------------- 1 | # Object-Oriented Programming with JavaScript 2 | 3 | Let's explore the key concepts of OOP in JavaScript, including examples of inheritance, encapsulation, polymorphism, private methods, public methods, and static methods. 4 | 5 | ## Table of Contents 6 | 1. [Objects in JavaScript](#objects-in-javascript) 7 | 2. [Creating Objects](#creating-objects) 8 | 3. [Prototypes and Inheritance](#prototypes-and-inheritance) 9 | 4. [Encapsulation](#encapsulation) 10 | 5. [Polymorphism](#polymorphism) 11 | 6. [Private and Public Methods](#private-and-public-methods) 12 | 7. [Static Methods](#static-methods) 13 | 14 | ## 1. Objects in JavaScript 15 | 16 | In JavaScript, everything is an object or can be treated as an object. Objects are instances of classes and can have properties and methods. 17 | 18 | ## 2. Creating Objects 19 | 20 | You can create objects using object literals or constructor functions. 21 | 22 | ```javascript 23 | // Using object literal 24 | let person = { 25 | name: 'John Doe', 26 | age: 25, 27 | greet: function() { 28 | console.log(`Hello, my name is ${this.name}.`); 29 | } 30 | }; 31 | 32 | // Using constructor function 33 | function Person(name, age) { 34 | this.name = name; 35 | this.age = age; 36 | } 37 | 38 | Person.prototype.greet = function() { 39 | console.log(`Hello, my name is ${this.name}.`); 40 | }; 41 | 42 | let john = new Person('John Doe', 25); 43 | john.greet(); 44 | ``` 45 | 46 | ## 3. Prototypes and Inheritance 47 | 48 | JavaScript uses prototypes for inheritance. Objects can inherit properties and methods from other objects. 49 | 50 | ```javascript 51 | // Inheritance using prototypes 52 | function Student(name, age, grade) { 53 | Person.call(this, name, age); 54 | this.grade = grade; 55 | } 56 | 57 | Student.prototype = Object.create(Person.prototype); 58 | Student.prototype.constructor = Student; 59 | 60 | let alice = new Student('Alice Smith', 20, 'A'); 61 | alice.greet(); 62 | ``` 63 | 64 | ## 4. Encapsulation 65 | 66 | Encapsulation is the bundling of data and the methods that operate on that data into a single unit, often referred to as a class. 67 | 68 | ```javascript 69 | // Encapsulation using constructor function 70 | function Car(make, model) { 71 | let speed = 0; // private variable 72 | 73 | this.getSpeed = function() { 74 | return speed; 75 | }; 76 | 77 | this.accelerate = function(amount) { 78 | speed += amount; 79 | }; 80 | 81 | this.brake = function(amount) { 82 | speed = Math.max(0, speed - amount); 83 | }; 84 | 85 | this.getInfo = function() { 86 | return `${make} ${model}, current speed: ${speed} km/h`; 87 | }; 88 | } 89 | 90 | let myCar = new Car('Toyota', 'Camry'); 91 | myCar.accelerate(30); 92 | console.log(myCar.getInfo()); 93 | ``` 94 | 95 | ## 5. Polymorphism 96 | 97 | Polymorphism allows objects of different classes to be treated as objects of a common class. 98 | 99 | ```javascript 100 | // Polymorphism with method overriding 101 | Person.prototype.introduce = function() { 102 | console.log(`Hi, I am ${this.name}.`); 103 | }; 104 | 105 | Student.prototype.introduce = function() { 106 | console.log(`Hi, I am ${this.name} and I am a student.`); 107 | }; 108 | 109 | john.introduce(); 110 | alice.introduce(); 111 | ``` 112 | 113 | ## 6. Private and Public Methods 114 | 115 | JavaScript doesn't have built-in support for private and public access modifiers, but conventions and closures can be used to achieve similar effects. 116 | 117 | ```javascript 118 | // Private and Public Methods 119 | function Counter() { 120 | let count = 0; // private variable 121 | 122 | function increment() { 123 | count++; 124 | } 125 | 126 | this.getCount = function() { 127 | increment(); // private method can be called from public method 128 | return count; 129 | }; 130 | } 131 | 132 | let myCounter = new Counter(); 133 | console.log(myCounter.getCount()); 134 | ``` 135 | 136 | ## 7. Static Methods 137 | 138 | Static methods are associated with the class itself rather than instances of the class. 139 | 140 | ```javascript 141 | // Static Method 142 | function MathUtils() {} 143 | 144 | MathUtils.add = function(a, b) { 145 | return a + b; 146 | }; 147 | 148 | console.log(MathUtils.add(2, 3)); 149 | ``` -------------------------------------------------------------------------------- /class-file/notes2/11.oop-javascript-class.md: -------------------------------------------------------------------------------- 1 | # Object-Oriented Programming with JavaScript Using Classes 2 | 3 | We'll explore the key concepts of OOP in JavaScript using classes, including examples of inheritance, encapsulation, polymorphism, private methods, public methods, and static methods. 4 | 5 | ## Table of Contents 6 | 1. [Classes in JavaScript](#classes-in-javascript) 7 | 2. [Creating Classes](#creating-classes) 8 | 3. [Inheritance with Classes](#inheritance-with-classes) 9 | 4. [Encapsulation](#encapsulation) 10 | 5. [Polymorphism](#polymorphism) 11 | 6. [Private and Public Methods](#private-and-public-methods) 12 | 7. [Static Methods](#static-methods) 13 | 14 | ## 1. Classes in JavaScript 15 | 16 | A class is a blueprint for creating objects with shared properties and methods. 17 | 18 | ```javascript 19 | // Class declaration 20 | class Person { 21 | constructor(name, age) { 22 | this.name = name; 23 | this.age = age; 24 | } 25 | 26 | greet() { 27 | console.log(`Hello, my name is ${this.name}.`); 28 | } 29 | } 30 | ``` 31 | 32 | ## 2. Creating Classes 33 | 34 | You can create instances of classes using the `new` keyword. 35 | 36 | ```javascript 37 | // Creating instances 38 | let john = new Person('John Doe', 25); 39 | john.greet(); 40 | ``` 41 | 42 | ## 3. Inheritance with Classes 43 | 44 | Classes support inheritance, allowing one class to inherit from another. 45 | 46 | ```javascript 47 | // Inheritance with classes 48 | class Student extends Person { 49 | constructor(name, age, grade) { 50 | super(name, age); 51 | this.grade = grade; 52 | } 53 | 54 | // Overriding the greet method 55 | greet() { 56 | console.log(`Hello, my name is ${this.name}, and I am a student.`); 57 | } 58 | } 59 | 60 | let alice = new Student('Alice Smith', 20, 'A'); 61 | alice.greet(); 62 | ``` 63 | 64 | ## 4. Encapsulation 65 | 66 | Encapsulation is achieved through the use of constructor functions and private properties. 67 | 68 | ```javascript 69 | // Encapsulation with classes 70 | class Car { 71 | #speed = 0; // private variable 72 | 73 | accelerate(amount) { 74 | this.#speed += amount; 75 | } 76 | 77 | brake(amount) { 78 | this.#speed = Math.max(0, this.#speed - amount); 79 | } 80 | 81 | getInfo() { 82 | return `Current speed: ${this.#speed} km/h`; 83 | } 84 | } 85 | 86 | let myCar = new Car(); 87 | myCar.accelerate(30); 88 | console.log(myCar.getInfo()); 89 | ``` 90 | 91 | ## 5. Polymorphism 92 | 93 | Polymorphism allows objects of different classes to be treated as objects of a common class. 94 | 95 | ```javascript 96 | // Polymorphism with method overriding 97 | class Animal { 98 | speak() { 99 | console.log('Animal speaks'); 100 | } 101 | } 102 | 103 | class Dog extends Animal { 104 | speak() { 105 | console.log('Dog barks'); 106 | } 107 | } 108 | 109 | let myAnimal = new Dog(); 110 | myAnimal.speak(); 111 | ``` 112 | 113 | ## 6. Private and Public Methods 114 | 115 | JavaScript classes have built-in support for public methods, but private methods can be achieved using naming conventions. 116 | 117 | ```javascript 118 | // Private and Public Methods 119 | class Counter { 120 | #count = 0; // private variable 121 | 122 | #increment() { 123 | this.#count++; 124 | } 125 | 126 | getCount() { 127 | this.#increment(); // private method can be called from public method 128 | return this.#count; 129 | } 130 | } 131 | 132 | let myCounter = new Counter(); 133 | console.log(myCounter.getCount()); 134 | ``` 135 | 136 | ## 7. Static Methods 137 | 138 | Static methods are associated with the class itself rather than instances of the class. 139 | 140 | ```javascript 141 | // Static Method 142 | class MathUtils { 143 | static add(a, b) { 144 | return a + b; 145 | } 146 | } 147 | 148 | console.log(MathUtils.add(2, 3)); 149 | ``` 150 | 151 | -------------------------------------------------------------------------------- /class-file/notes2/12.Introduction-to-async.md: -------------------------------------------------------------------------------- 1 | Topic: Understanding Synchronous and Asynchronous Programming in Node.js 2 | 3 | 1. Difference between Synchronous and Asynchronous: 4 | 5 | Synchronous Programming: 6 | - Synchronous programming refers to the execution of code in a sequential order, where one task must finish before the next one begins. 7 | - In synchronous code, each operation waits for the previous one to complete before executing. 8 | - Example: 9 | ```javascript 10 | console.log('Start'); 11 | console.log('Middle'); 12 | console.log('End'); 13 | ``` 14 | Output: 15 | ``` 16 | Start 17 | Middle 18 | End 19 | ``` 20 | 21 | Asynchronous Programming: 22 | - Asynchronous programming allows multiple operations to be executed concurrently, without waiting for the previous operation to complete. 23 | - In asynchronous code, tasks are initiated and executed independently, and their results are handled through callbacks or promises. 24 | - Example: 25 | ```javascript 26 | console.log('Start'); 27 | setTimeout(() => { 28 | console.log('Async operation completed'); 29 | }, 2000); 30 | console.log('End'); 31 | ``` 32 | Output: 33 | ``` 34 | Start 35 | End 36 | Async operation completed (after approximately 2 seconds) 37 | ``` 38 | 39 | 2. Node.js Event Loop: 40 | 41 | - Node.js is single-threaded, meaning it can handle only one operation at a time. 42 | - The Node.js event loop is a mechanism that allows Node.js to perform non-blocking I/O operations despite being single-threaded. 43 | - It manages asynchronous operations by executing them in the background and processing their results when they become available. 44 | - The event loop continuously checks for tasks in the event queue and executes them one by one. 45 | - Example: 46 | ```javascript 47 | const fs = require('fs'); 48 | 49 | console.log('Start reading file...'); 50 | fs.readFile('example.txt', (err, data) => { 51 | if (err) throw err; 52 | console.log('File content:', data.toString()); 53 | }); 54 | console.log('End of script'); 55 | ``` 56 | In this example, the file reading operation is non-blocking, and the event loop continues to execute other tasks while waiting for the file operation to complete. 57 | 58 | 3. How Asynchronous Operations Work: 59 | 60 | - Asynchronous operations in Node.js are handled using callbacks, promises, or async/await syntax. 61 | - Callbacks are functions passed as arguments to other functions, to be executed once the asynchronous operation is completed. 62 | - Promises provide a cleaner and more structured way to handle asynchronous operations, allowing chaining of multiple asynchronous tasks. 63 | - Async/await is a modern syntax introduced in ES8 (ECMAScript 2017), which allows writing asynchronous code in a synchronous style using the `async` and `await` keywords. 64 | - Example using Callbacks: 65 | ```javascript 66 | function fetchData(callback) { 67 | setTimeout(() => { 68 | callback('Data fetched successfully'); 69 | }, 2000); 70 | } 71 | 72 | console.log('Start fetching data...'); 73 | fetchData((result) => { 74 | console.log(result); 75 | }); 76 | console.log('End of script'); 77 | ``` 78 | Output: 79 | ``` 80 | Start fetching data... 81 | End of script 82 | Data fetched successfully (after approximately 2 seconds) 83 | ``` 84 | 85 | - Example using Promises: 86 | ```javascript 87 | function fetchData() { 88 | return new Promise((resolve, reject) => { 89 | setTimeout(() => { 90 | resolve('Data fetched successfully'); 91 | }, 2000); 92 | }); 93 | } 94 | 95 | console.log('Start fetching data...'); 96 | fetchData() 97 | .then((result) => { 98 | console.log(result); 99 | }) 100 | .catch((error) => { 101 | console.error(error); 102 | }); 103 | console.log('End of script'); 104 | ``` 105 | Output: 106 | ``` 107 | Start fetching data... 108 | End of script 109 | Data fetched successfully (after approximately 2 seconds) 110 | ``` 111 | 112 | - Example using Async/Await: 113 | ```javascript 114 | async function fetchData() { 115 | return new Promise((resolve, reject) => { 116 | setTimeout(() => { 117 | resolve('Data fetched successfully'); 118 | }, 2000); 119 | }); 120 | } 121 | 122 | async function fetchDataAndDisplay() { 123 | try { 124 | console.log('Start fetching data...'); 125 | const result = await fetchData(); 126 | console.log(result); 127 | } catch (error) { 128 | console.error(error); 129 | } 130 | } 131 | 132 | console.log('Start of script'); 133 | fetchDataAndDisplay(); 134 | console.log('End of script'); 135 | ``` 136 | Output: 137 | ``` 138 | Start of script 139 | Start fetching data... 140 | End of script 141 | Data fetched successfully (after approximately 2 seconds) 142 | ``` 143 | -------------------------------------------------------------------------------- /class-file/notes2/13.more-on-async.md: -------------------------------------------------------------------------------- 1 | **1. Understanding Asynchronous JavaScript and Promises** 2 | 3 | JavaScript, being a single-threaded language, executes code sequentially by default. However, in modern web development, many tasks, such as fetching data from an API or reading files, take time to complete. Asynchronous JavaScript allows us to perform these tasks without blocking the main thread, ensuring a smooth and responsive user experience. 4 | 5 | **Example:** 6 | 7 | ```javascript 8 | console.log("Before"); 9 | 10 | setTimeout(() => { 11 | console.log("Inside setTimeout"); 12 | }, 2000); 13 | 14 | console.log("After"); 15 | ``` 16 | 17 | In the above example, "Before" and "After" are logged immediately, while "Inside setTimeout" is logged after a delay of 2000 milliseconds. 18 | 19 | **2. Asynchronous Programming with Callbacks** 20 | 21 | Callbacks are a fundamental part of asynchronous JavaScript programming. They are functions passed as arguments to another function, to be executed later when a certain event occurs or a task is completed. 22 | 23 | **Example:** 24 | 25 | ```javascript 26 | function fetchData(callback) { 27 | setTimeout(() => { 28 | callback("Data fetched successfully"); 29 | }, 2000); 30 | } 31 | 32 | fetchData((data) => { 33 | console.log(data); 34 | }); 35 | ``` 36 | 37 | In this example, `fetchData` takes a callback function as an argument and executes it after a delay. This pattern is common in Node.js and browser APIs like `fetch`. 38 | 39 | **3. Introduction to Promises for Handling Async Operations** 40 | 41 | Promises provide a cleaner and more structured way to handle asynchronous operations compared to callbacks. A Promise represents the eventual completion or failure of an asynchronous operation, and it allows chaining multiple asynchronous operations together. 42 | 43 | **Example:** 44 | 45 | ```javascript 46 | function fetchData() { 47 | return new Promise((resolve, reject) => { 48 | setTimeout(() => { 49 | resolve("Data fetched successfully"); 50 | }, 2000); 51 | }); 52 | } 53 | 54 | fetchData() 55 | .then((data) => { 56 | console.log(data); 57 | }) 58 | .catch((error) => { 59 | console.error(error); 60 | }); 61 | ``` 62 | 63 | Here, `fetchData` returns a Promise that resolves with the fetched data after 2 seconds. We can use `.then()` to handle the resolved value and `.catch()` to handle any errors. 64 | 65 | **4. JavaScript Async/Await Operations** 66 | 67 | Async/await is a modern syntax introduced in ES8 (ES2017) that further simplifies asynchronous programming. It allows writing asynchronous code in a synchronous-like manner, making it easier to read and understand. 68 | 69 | **Example:** 70 | 71 | ```javascript 72 | async function fetchData() { 73 | return new Promise((resolve) => { 74 | setTimeout(() => { 75 | resolve("Data fetched successfully"); 76 | }, 2000); 77 | }); 78 | } 79 | 80 | async function getData() { 81 | try { 82 | const data = await fetchData(); 83 | console.log(data); 84 | } catch (error) { 85 | console.error(error); 86 | } 87 | } 88 | 89 | getData(); 90 | ``` 91 | 92 | In this example, `fetchData` returns a Promise, and `getData` uses `await` to pause execution until the Promise is resolved. This makes the code appear synchronous while maintaining asynchrony under the hood. 93 | 94 | **5. Error Handling with try...catch** 95 | 96 | Async/await also simplifies error handling by allowing the use of `try...catch` blocks around asynchronous code, making it similar to synchronous error handling. 97 | 98 | **Example:** 99 | 100 | ```javascript 101 | async function fetchData() { 102 | return new Promise((resolve, reject) => { 103 | setTimeout(() => { 104 | reject("Error: Unable to fetch data"); 105 | }, 2000); 106 | }); 107 | } 108 | 109 | async function getData() { 110 | try { 111 | const data = await fetchData(); 112 | console.log(data); 113 | } catch (error) { 114 | console.error(error); 115 | } 116 | } 117 | 118 | getData(); 119 | ``` 120 | -------------------------------------------------------------------------------- /class-file/notes3/14.es6-features.md: -------------------------------------------------------------------------------- 1 | 2 | ### ES6 (ECMAScript 2015) 3 | 4 | - **`let` and `const`** 5 | - `let` is used for block-scoped variables that can be reassigned. 6 | - `const` is used for block-scoped constants that cannot be reassigned. 7 | ```javascript 8 | let count = 1; 9 | count += 1; // OK 10 | 11 | const PI = 3.14; 12 | // PI = 3; // Error: Assignment to constant variable. 13 | ``` 14 | 15 | - **Arrow Functions** 16 | - Provide a concise syntax for writing function expressions. 17 | ```javascript 18 | const add = (a, b) => a + b; 19 | ``` 20 | 21 | - **Template Literals** 22 | - Extended string literals supporting interpolation and multi-line strings. 23 | ```javascript 24 | const name = 'World'; 25 | console.log(`Hello, ${name}!`); 26 | ``` 27 | 28 | - **Default Parameters** 29 | - Functions can have default values for parameters. 30 | ```javascript 31 | function greet(name = 'World') { 32 | console.log(`Hello, ${name}!`); 33 | } 34 | ``` 35 | 36 | - **Destructuring Assignment** 37 | - Allows unpacking values from arrays or properties from objects. 38 | ```javascript 39 | const [a, b] = [1, 2]; 40 | const {x, y} = {x: 10, y: 20}; 41 | ``` 42 | 43 | - **Enhanced Object Literals** 44 | - Shorthand syntax for initializing properties and defining methods. 45 | ```javascript 46 | const x = 10, y = 20; 47 | const obj = { x, y, method() { return x + y; } }; 48 | ``` 49 | 50 | - **Promises** 51 | - Represents the eventual completion (or failure) of an asynchronous operation. 52 | ```javascript 53 | const promise = new Promise((resolve, reject) => { 54 | // Async operation here; call resolve() or reject() 55 | }); 56 | ``` 57 | 58 | - **Classes** 59 | - Syntactic sugar over JavaScript's prototype-based inheritance. 60 | ```javascript 61 | class Person { 62 | constructor(name) { 63 | this.name = name; 64 | } 65 | greet() { 66 | console.log(`Hello, ${this.name}!`); 67 | } 68 | } 69 | ``` 70 | 71 | - **Modules** 72 | - Support for `import` and `export` statements. 73 | ```javascript 74 | // In a file named 'module.js' 75 | export const PI = 3.14; 76 | export function add(a, b) { 77 | return a + b; 78 | } 79 | 80 | // In another file 81 | import { PI, add } from './module.js'; 82 | ``` 83 | 84 | - **Spread Operator** 85 | - Allows an iterable to be expanded where arguments or elements are expected. 86 | ```javascript 87 | const nums = [1, 2, 3]; 88 | const moreNums = [...nums, 4, 5]; // [1, 2, 3, 4, 5] 89 | ``` 90 | 91 | - **Rest Parameters** 92 | - Represents an indefinite number of arguments as an array. 93 | ```javascript 94 | function sum(...nums) { 95 | return nums.reduce((a, b) => a + b, 0); 96 | } 97 | ``` 98 | 99 | ### ES7 (ECMAScript 2016) 100 | 101 | - **Array.prototype.includes()** 102 | - Checks if an array includes a certain value. 103 | ```javascript 104 | const arr = [1, 2, 3]; 105 | console.log(arr.includes(2)); // true 106 | ``` 107 | 108 | - **Exponentiation Operator** 109 | - New syntax for exponentiation (`Math.pow` equivalent). 110 | ```javascript 111 | console.log(2 ** 3); // 8 112 | ``` 113 | 114 | ### ES8 (ECMAScript 2017) 115 | 116 | - **`async`/`await`** 117 | - Syntactic sugar making asynchronous code look synchronous. 118 | ```javascript 119 | async function fetchData() { 120 | const data = await fetch('url'); 121 | const json = await data.json(); 122 | return json; 123 | } 124 | ``` 125 | 126 | - **Object.values() and Object.entries()** 127 | - Return an object's enumerable property values and key-value pairs. 128 | ```javascript 129 | const obj = { a: 1, b: 2 }; 130 | console.log(Object.values(obj)); // [1, 2] 131 | console.log(Object.entries(obj)); // [['a', 1], ['b', 2]] 132 | ``` 133 | 134 | ### ES9 (ECMAScript 2018) 135 | 136 | - **Rest/Spread Properties for Object Literals** 137 | - Spread properties for object literals and rest properties for destructuring. 138 | ```javascript 139 | const { a, ...rest } = { a: 1, b: 2, c: 3 }; 140 | console.log(rest); // { b: 2, c: 3 } 141 | ``` 142 | 143 | ### ES10 (ECMAScript 2019) 144 | 145 | 146 | 147 | - **`Array.prototype.flat()`** 148 | - Flattens arrays to a specified depth. 149 | ```javascript 150 | const arr = [1, [2, [3]]]; 151 | console.log(arr.flat(2)); // [1, 2, 3] 152 | ``` 153 | 154 | ### ES11 (ECMAScript 2020) 155 | 156 | - **BigInt** 157 | - Represents integers larger than 2^53 - 1. 158 | ```javascript 159 | const bigNumber = 1234567890123456789012345678901234567890n; 160 | ``` 161 | 162 | - **Optional Chaining** 163 | - Access deeply nested properties without having to check each reference in the chain. 164 | ```javascript 165 | const obj = { a: { b: { c: 1 } } }; 166 | console.log(obj?.a?.b?.c); // 1 167 | ``` 168 | 169 | - **Nullish Coalescing Operator** 170 | - Logical operator returning its right-hand side operand when the left-hand side is `null` or `undefined`. 171 | ```javascript 172 | const foo = null ?? 'default string'; 173 | console.log(foo); // 'default string' 174 | ``` -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 | 10 | 11 | 12 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /js/array.js: -------------------------------------------------------------------------------- 1 | let mountains = ['Evest', 'Fuji', 'Nanga Parbat']; 2 | console.log(mountains); // 'Everest' 3 | 4 | mountains[0] = 'Everest' 5 | console.log(mountains); // 'Everest' 6 | 7 | 8 | console.log(mountains.length) 9 | 10 | 11 | let locations = new Array(); 12 | 13 | console.log(locations) 14 | 15 | locations.push("Abuja") 16 | locations.push("Lagos") 17 | locations.push(["Delta", "Calabar"]) 18 | 19 | console.log(locations.indexOf('Abuja')) 20 | 21 | let arrayOfObjects = [ 22 | { 23 | employee_id: 1, 24 | employee_name: "John Doe", 25 | employee_department: "IT" 26 | }, 27 | { 28 | employee_id: 2, 29 | employee_name: "Mary Doe", 30 | employee_department: "HR" 31 | } 32 | ] 33 | 34 | console.table(arrayOfObjects) -------------------------------------------------------------------------------- /js/class-example.md: -------------------------------------------------------------------------------- 1 | 2 | # Example class definition of an Employee Record System 3 | 4 | ```javascript 5 | class Employee { 6 | constructor(name, employeeId, position) { 7 | this.name = name; 8 | this.employeeId = employeeId; 9 | this.position = position; 10 | } 11 | 12 | getDetails() { 13 | return `Name: ${this.name}, Employee ID: ${this.employeeId}, Position: ${this.position}`; 14 | } 15 | 16 | work() { 17 | console.log(`${this.name} is performing regular work tasks.`); 18 | } 19 | } 20 | 21 | class AdminEmployee extends Employee { 22 | constructor(name, employeeId, position, department) { 23 | super(name, employeeId, position); 24 | this.department = department; 25 | } 26 | 27 | getDetails() { 28 | // Overriding the getDetails method to include the department 29 | return `${super.getDetails()}, Department: ${this.department}`; 30 | } 31 | 32 | manageEmployees() { 33 | console.log(`${this.name} is managing other employees.`); 34 | } 35 | 36 | accessSensitiveInformation() { 37 | console.log(`${this.name} has access to sensitive information.`); 38 | } 39 | } 40 | 41 | // Creating instances of Employee and AdminEmployee 42 | let regularEmployee = new Employee('John Doe', 'E001', 'Software Developer'); 43 | let adminEmployee = new AdminEmployee('Admin Smith', 'A001', 'IT Manager', 'IT Department'); 44 | 45 | // Displaying details 46 | console.log(regularEmployee.getDetails()); 47 | console.log(adminEmployee.getDetails()); 48 | 49 | // Regular employee performing work 50 | regularEmployee.work(); 51 | 52 | // Admin employee performing work and additional actions 53 | adminEmployee.work(); 54 | adminEmployee.manageEmployees(); 55 | adminEmployee.accessSensitiveInformation(); 56 | ``` 57 | 58 | In this example: 59 | 60 | - The `Employee` class has basic properties like name, employee ID, and position, along with methods like `getDetails` and `work`. 61 | - The `AdminEmployee` class inherits from `Employee` and extends its functionality by including a `department` property and additional methods like `manageEmployees` and `accessSensitiveInformation`. 62 | - Instances of both classes are created, and you can see how the AdminEmployee has access to the methods of the Employee class and adds its own methods for managing employees and accessing sensitive information. 63 | -------------------------------------------------------------------------------- /js/class/class1.js: -------------------------------------------------------------------------------- 1 | class Person { 2 | constructor(name, age) { 3 | this.name = name 4 | this.age = age 5 | 6 | // perform some other actions 7 | } 8 | 9 | // this is a method 10 | printDetails() { 11 | return `This person's name is ${this.name}, and this person's age is ${this.age}` 12 | } 13 | } 14 | 15 | let john = new Person("John James", 45) 16 | 17 | console.log(john.printDetails()) -------------------------------------------------------------------------------- /js/class/class2.js: -------------------------------------------------------------------------------- 1 | class Human { 2 | constructor(name, age, hands, legs) { 3 | this.name = name 4 | this.age = age 5 | this.hand = hands 6 | this.legs = legs 7 | } 8 | 9 | walk() { 10 | return `${this.name} is walking` 11 | } 12 | 13 | eat() { 14 | return `${this.name} is eating` 15 | } 16 | } 17 | 18 | let marv = new Human("Marv Magic", 40, 2, 2) 19 | 20 | console.log(marv.eat()) -------------------------------------------------------------------------------- /js/class/encapsulation.js: -------------------------------------------------------------------------------- 1 | // Encapsulation with classes 2 | class Car { 3 | #speed = 0; // private variable 4 | 5 | accelerate(amount) { 6 | this.#speed += amount; 7 | } 8 | 9 | brake(amount) { 10 | this.#speed = Math.max(0, this.#speed - amount); 11 | } 12 | 13 | getInfo() { 14 | return `Current speed: ${this.#speed} km/h`; 15 | } 16 | } 17 | 18 | let myCar = new Car(); 19 | myCar.accelerate(30); 20 | console.log(myCar.getInfo()); -------------------------------------------------------------------------------- /js/class/inheritance.js: -------------------------------------------------------------------------------- 1 | // Class declaration 2 | class Person { 3 | constructor(name, age) { 4 | this.name = name; 5 | this.age = age; 6 | } 7 | 8 | greet() { 9 | console.log(`Hello, my name is ${this.name}.`); 10 | } 11 | } 12 | 13 | // Inheritance with classes 14 | class Student extends Person { 15 | constructor(name, age, grade) { 16 | super(name, age); 17 | this.grade = grade; 18 | } 19 | 20 | // Overriding the greet method 21 | greet() { 22 | console.log(`Hello, my name is ${this.name}, and I am a student.`); 23 | } 24 | } 25 | 26 | let alice = new Student('Alice Smith', 20, 'A'); 27 | alice.greet(); -------------------------------------------------------------------------------- /js/class/polymorphism.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/solomonmarvel97/300devdays-introduction-to-js/d4089020acd50124533d530fc09e8903582a3b42/js/class/polymorphism.js -------------------------------------------------------------------------------- /js/class/practice/employee.js: -------------------------------------------------------------------------------- 1 | class Employee { 2 | constructor(name, employeeId, position) { 3 | this.name = name 4 | this.employeeId = employeeId 5 | this.position = position 6 | } 7 | 8 | getDetails() { 9 | return `Name: ${this.name}, Employee ID: ${this.employeeId}, Position: ${this.position}` 10 | } 11 | 12 | work() { 13 | console.log(`${this.namee} is performing regular tasks`) 14 | } 15 | } 16 | 17 | 18 | // perform inheritance 19 | 20 | class AdminEmployee extends Employee { 21 | constructor(name, employeeId, position, department) { 22 | super(name, employeeId, position) 23 | this.department = department 24 | } 25 | 26 | // polymorphism 27 | getDetails() { 28 | // overriding the getDetails method to include the department 29 | return `${super.getDetails()}, Department: ${this.department}` 30 | } 31 | 32 | manageEmployees() { 33 | console.log(`${this.name}, is managing other employees`) 34 | } 35 | 36 | accessSensitiveInformation() { 37 | console.log(`${this.name} can access sensitive information`) 38 | } 39 | } 40 | 41 | 42 | // creating the instances 43 | 44 | let regularEmployee = new Employee('John Doe', '12412', 'Software Developer') 45 | let adminEmployee = new AdminEmployee('John James', '121231', 'IT Manager', "IT Department") 46 | 47 | // Display Details 48 | console.log(regularEmployee.getDetails()) 49 | console.log(adminEmployee.getDetails()) 50 | 51 | adminEmployee.manageEmployees() -------------------------------------------------------------------------------- /js/class/practice/product.js: -------------------------------------------------------------------------------- 1 | class Product { 2 | constructor(productId, name, price) { 3 | this.productId = productId 4 | this.name = name 5 | this.price = price 6 | } 7 | 8 | create() { 9 | // Save the record to the database 10 | let productObject = { 11 | productId : this.productId, 12 | productName: this.name, 13 | productPrice: this.price 14 | } 15 | productObject.message = "The product was created successfully" 16 | 17 | return productObject 18 | } 19 | 20 | static delete(id) { 21 | // run a query to delete the record 22 | // from the database given the specific id 23 | // passed into the static method 24 | 25 | return "Product was deleted successfully" 26 | } 27 | } 28 | 29 | let appleDrink = new Product(14122, "Apple Drink", 1000) 30 | 31 | console.log(appleDrink.create()) 32 | 33 | Product.delete(14122) -------------------------------------------------------------------------------- /js/class/staticmethods.js: -------------------------------------------------------------------------------- 1 | // Static Method 2 | class MathUtils { 3 | static add(a, b) { 4 | return a + b; 5 | } 6 | } 7 | 8 | console.log(MathUtils.add(2, 3)); -------------------------------------------------------------------------------- /js/example1.js: -------------------------------------------------------------------------------- 1 | let fruits = ["apple", "orange", "banana", 1]; 2 | console.log(fruits) -------------------------------------------------------------------------------- /js/main.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * This is a simple function to check 4 | * if a user exists in our database or not 5 | */ 6 | function userExistsInDB(email, check) { 7 | 8 | //call db to check if the user exist 9 | return check 10 | } 11 | 12 | function respondToUser(email) { 13 | let condition = userExistsInDB(email, false) 14 | 15 | if(condition) { 16 | return "User Exists in DB" 17 | } else { 18 | return "User not found" 19 | } 20 | } 21 | 22 | let result = respondToUser("johndoe@email.com") 23 | console.log(result) -------------------------------------------------------------------------------- /js/objects.js: -------------------------------------------------------------------------------- 1 | let emptyObject = {} 2 | console.log(emptyObject) 3 | 4 | emptyObject.newProperty = "Hello World" 5 | console.log(emptyObject) 6 | 7 | let person = { 8 | firstName: 'John', 9 | lastName: 'Doe', 10 | age: 45, 11 | department: "Computer Science", 12 | role: "Lecturer" 13 | }; 14 | 15 | console.log(person) 16 | 17 | let human = { 18 | legs : 2, 19 | hands: 2, 20 | head: 1, 21 | } 22 | 23 | console.log(human.legs + " legs") 24 | 25 | human['eyes'] = 2 26 | human.eyes = 2 27 | human.legs = 3 28 | console.log(human) 29 | 30 | let employee = { 31 | name: "John Doe", 32 | dob: "1/1/1990", 33 | department: "IT", 34 | role: "DevOps Engineer" 35 | } 36 | 37 | console.table(employee) 38 | // delete employee.role 39 | 40 | console.log('role' in employee) -------------------------------------------------------------------------------- /js/strings.js: -------------------------------------------------------------------------------- 1 | // Single quotes 2 | let strSingle = 'Hello ma"am'; 3 | 4 | // Double quotes 5 | let strDouble = "Hello ma'am"; 6 | 7 | 8 | // Template literals 9 | let templateStr = `JavaScript is ${strSingle} ${strDouble}!`; 10 | 11 | let firstName = "John" 12 | let lastName = "Doe" 13 | let age = 35 14 | 15 | let fullName = firstName + " " + lastName + " is " + age + " years old." 16 | let fullName2 = `${firstName} ${lastName} is ${age} years old.` 17 | 18 | 19 | let originalStr = 'CODE SCHOOL'; 20 | let modifiedStr = originalStr.toLowerCase(); 21 | 22 | console.log(originalStr); // Output: Immutable 23 | console.log(modifiedStr); // Output: IMMUTABLE 24 | 25 | 26 | let specialStr = 'I\'m a string with a single quote!'; 27 | console.log(specialStr) 28 | 29 | 30 | let stringText = "I am a programmer based in Nigeria"; 31 | console.log(stringText.length); 32 | 33 | 34 | let str = "Hello1"; 35 | console.log(str[5]); // Output: "o" 36 | // console.log(str[str.length - 1]); 37 | 38 | let classNumber = 1872 39 | console.log(String(classNumber)) 40 | -------------------------------------------------------------------------------- /note2jsfiles/intro-to-asnyc.js: -------------------------------------------------------------------------------- 1 | function fetchData() { 2 | return new Promise((resolve, reject) => { 3 | let result = true 4 | 5 | setTimeout(() => { 6 | if(result) { 7 | resolve("Success") 8 | } else { 9 | reject("Error") 10 | } 11 | 12 | 13 | reject('Sorry an error occured here'); 14 | }, 2000); 15 | }); 16 | } 17 | 18 | console.log('Start fetching data...'); 19 | fetchData() 20 | .then((result) => { 21 | console.log(result); 22 | }) 23 | .catch((error) => { 24 | console.error(error); 25 | }); 26 | console.log('End of script'); -------------------------------------------------------------------------------- /note2jsfiles/intro-to-async2.js: -------------------------------------------------------------------------------- 1 | async function checkIfEmailExists(email) { 2 | // call the database 3 | // SELECT * FROM DB where email=email 4 | throw new Error("Invalid email format") 5 | return true 6 | } 7 | 8 | async function createUserRecord(email, password) { 9 | try { 10 | // check if the record already exist 11 | const ifRecordExist = await checkIfEmailExists(email) //undefined 12 | if (ifRecordExist) { 13 | return "This record already exist in our system" 14 | } else { 15 | // create a new record in the db 16 | createRecordInTheDatabase() 17 | } 18 | } 19 | catch (err) { 20 | return err 21 | } 22 | } 23 | 24 | 25 | 26 | // async function fetchData() { 27 | // return new Promise((resolve, reject) => { 28 | // setTimeout(() => { 29 | // resolve('Data fetched successfully'); 30 | // }, 2000); 31 | // }); 32 | // } 33 | 34 | // async function fetchDataAndDisplay() { 35 | // try { 36 | // console.log('Start fetching data...'); 37 | // const result = await fetchData(); 38 | // //console.log(result); 39 | // } catch (error) { 40 | // console.error(error); 41 | // } 42 | // } 43 | 44 | // console.log('Start of script'); 45 | // fetchDataAndDisplay(); 46 | // console.log('End of script'); -------------------------------------------------------------------------------- /note3jsfiles/file2.js: -------------------------------------------------------------------------------- 1 | // commonjs 2 | function greet(greeting) { 3 | return `Good ${greeting}` 4 | } 5 | 6 | function call(phoneNumber) { 7 | return `Call ${phoneNumber}` 8 | } 9 | 10 | // commonjs export 11 | module.export = { 12 | greet, 13 | call 14 | } 15 | 16 | // commonjs import 17 | const {greet, call } = require("./jsfile.js") 18 | 19 | 20 | // es6 export 21 | export const PI = 3.14; 22 | export function add(a, b) { 23 | return a + b; 24 | } 25 | 26 | // import in es6 27 | import { PI, add } from './module.js'; -------------------------------------------------------------------------------- /note3jsfiles/main.js: -------------------------------------------------------------------------------- 1 | class User { 2 | constructor(email) { 3 | this.email = email 4 | } 5 | 6 | validateEmail() { 7 | // Regular expression to validate email format 8 | const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; 9 | if (re.test(this.email)) { 10 | console.log("The email is valid") 11 | return this 12 | } else { 13 | console.log("The email is invalid") 14 | throw "The email does not meet our validation requirements" 15 | } 16 | } 17 | 18 | saveRecord() { 19 | console.log("The record was saved") 20 | } 21 | } 22 | 23 | // const user1 = new User("me@.com") 24 | // user1.validateEmail() 25 | // .saveRecord() 26 | 27 | 28 | // Array.prototype.includes() 29 | 30 | const arr = [1, 5, 3]; 31 | console.log(arr.includes(2)); // true 32 | 33 | 34 | // Object.values() and Object.entries() 35 | 36 | const obj = { a: 1, b: 2 }; 37 | console.log(Object.values(obj)); // [1, 2] 38 | console.log(Object.entries(obj)); // [['a', 1], ['b', 2]] 39 | 40 | 41 | // Rest/Spread Properties for Object Literals 42 | 43 | const { a, b, ...rest } = { a: 1, b: 2, c: 3, d: 5 }; 44 | console.log(rest); // { b: 2, c: 3 } 45 | 46 | 47 | // Optional Chaining 48 | 49 | const obj1 = { a: { b: { c: 1 } } }; 50 | console.log(obj1?.a?.b?.c); // 1 51 | 52 | 53 | // Nullish Coalescing Operator 54 | 55 | function callAPI() { 56 | return null 57 | } 58 | 59 | const foo = callAPI() ?? 'nothing was returned'; 60 | console.log(foo); // 'default string' -------------------------------------------------------------------------------- /note3jsfiles/restparamters.js: -------------------------------------------------------------------------------- 1 | function sum(...nums) { 2 | return nums.reduce((a, b) => a + b, 0); 3 | } 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /note3jsfiles/spreadoperator.js: -------------------------------------------------------------------------------- 1 | const nums = [1, 2, 3]; 2 | const moreNums = [...nums, 4, 5]; // [1, 2, 3, 4, 5] 3 | 4 | console.log(moreNums) -------------------------------------------------------------------------------- /note5jsfiles/authHelper.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This is the function for hashing 3 | * user password 4 | * @param {string} originalPassword 5 | * @returns 6 | */ 7 | exports.hashUserPassword = function (originalPassword) { 8 | let hashedPassword = `1226162${originalPassword}` // contain the function for hashing the password 9 | return hashedPassword 10 | } 11 | 12 | /** 13 | * Return true or false when checking email validity 14 | * @param {string} originalEmail 15 | * @returns 16 | */ 17 | exports.checkEmailValidity = function(originalEmail) { 18 | let isEmailValid = true // call a function to validate email 19 | return isEmailValid 20 | } 21 | -------------------------------------------------------------------------------- /note5jsfiles/employeeChecks.js: -------------------------------------------------------------------------------- 1 | function computeEmployeeTax(salary){ 2 | return salary * 10 / 100 3 | } 4 | 5 | function computeBirthdayCheck(){ 6 | return "Employee's birthday" 7 | } -------------------------------------------------------------------------------- /note5jsfiles/main.js: -------------------------------------------------------------------------------- 1 | const {hashUserPassword} = require('./authHelper') 2 | 3 | console.log(hashUserPassword('helloworld')) -------------------------------------------------------------------------------- /note5jsfiles/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "note5jsfiles", 3 | "type" : "commonjs", 4 | "version": "1.0.0", 5 | "description": "", 6 | "main": "main.js", 7 | "scripts": { 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "keywords": [], 11 | "author": "", 12 | "license": "ISC" 13 | } 14 | -------------------------------------------------------------------------------- /practice-sessions/practice1.js: -------------------------------------------------------------------------------- 1 | class Product { 2 | constructor(name, price) { 3 | this._name = name 4 | this._price = price 5 | } 6 | 7 | // Encapsulation 8 | getName() { 9 | return this._name 10 | } 11 | 12 | setName(newName) { 13 | this._name = newName 14 | } 15 | 16 | getPrice() { 17 | return this._price 18 | } 19 | 20 | setPrice(newPrice) { 21 | this._price = newPrice 22 | } 23 | 24 | calculateTotalPrice(quantity) { 25 | return this._price * quantity 26 | } 27 | 28 | static currencyConverter(price, exchangeRate) { 29 | return price * exchangeRate 30 | } 31 | } 32 | 33 | let product1 = new Product("Football", 1000) 34 | 35 | console.log(product1.getPrice()) 36 | 37 | product1.setPrice(10_000) 38 | 39 | console.log(product1.getPrice()) 40 | 41 | // calculate total price if we need to purchase 5 football 42 | let totalPrice = product1.calculateTotalPrice(5) 43 | console.log(totalPrice) 44 | 45 | let exchangeRateInNGN = Product.currencyConverter(product1._price, 1400) 46 | console.log(exchangeRateInNGN) 47 | -------------------------------------------------------------------------------- /practice-sessions/practice2.js: -------------------------------------------------------------------------------- 1 | 2 | class Customer { 3 | constructor(name, email) { 4 | this._name = name 5 | this._email = email 6 | } 7 | 8 | getName() { 9 | return this._name 10 | } 11 | 12 | // this method changes the name of the customer 13 | setName(newName) { 14 | this._name = newName 15 | } 16 | 17 | getEmail() { 18 | return this._email 19 | } 20 | 21 | setEmail(newEmail) { 22 | this._email = newEmail 23 | } 24 | 25 | static sendPromotion(customer, promotion) { 26 | let message = `Hi ${customer.getName()}, ${promotion}` 27 | return message 28 | } 29 | 30 | } 31 | 32 | let customer1 = new Customer("John", "john@email.com") 33 | 34 | console.log(customer1.getEmail()) 35 | 36 | customer1.setEmail("johnmark@outlook.com") 37 | 38 | console.log(customer1.getEmail()) 39 | 40 | let promo = Customer.sendPromotion(customer1, "You just got yourself a free monthly sub") 41 | 42 | console.log(promo) 43 | -------------------------------------------------------------------------------- /practice-sessions/practice3.js: -------------------------------------------------------------------------------- 1 | class Product { 2 | constructor(name, price) { 3 | this._name = name 4 | this._price = price 5 | } 6 | 7 | // Encapsulation 8 | getName() { 9 | return this._name 10 | } 11 | 12 | setName(newName) { 13 | this._name = newName 14 | } 15 | 16 | getPrice() { 17 | return this._price 18 | } 19 | 20 | setPrice(newPrice) { 21 | this._price = newPrice 22 | } 23 | 24 | calculateTotalPrice(quantity) { 25 | return this._price * quantity 26 | } 27 | 28 | static currencyConverter(price, exchangeRate) { 29 | return price * exchangeRate 30 | } 31 | } 32 | 33 | // Creating the base user model 34 | 35 | class User { 36 | constructor(name, email) { 37 | this._name = name 38 | this._email = email 39 | } 40 | 41 | getName() { 42 | return this._name 43 | } 44 | 45 | setName(newName) { 46 | this._name = newName 47 | } 48 | 49 | getEmail() { 50 | return this._email 51 | } 52 | 53 | setEmail(newEmail) { 54 | this._email = newEmail 55 | } 56 | 57 | viewProfile() { 58 | return `User: ${this._name}, Email: ${this._email}` 59 | } 60 | } 61 | 62 | class RegularUser extends User { 63 | constructor(name, email) { 64 | super(name, email) 65 | this._type = "Regular" 66 | } 67 | 68 | getType() { 69 | return this._type 70 | } 71 | 72 | // Additional action for the user 73 | placeOrder(product) { 74 | return `The product with the name ${product.getName()} has the price of ${product.getPrice()}. Order was placed successfully` 75 | } 76 | } 77 | 78 | let user1 = new RegularUser("john doe", "johndoe@gmail.com") 79 | console.log(user1.getName()) 80 | console.log(user1.getEmail()) 81 | console.log(user1.viewProfile()) 82 | console.log(user1.getType()) 83 | 84 | let product1 = new Product("Vanilla Ice Cream", "100_000") 85 | 86 | let result = user1.placeOrder(product1) 87 | 88 | console.log(result) 89 | 90 | console.log("########################################") 91 | 92 | 93 | let user2 = new RegularUser("john mary", "johnmary@gmail.com") 94 | console.log(user2.getName()) 95 | console.log(user2.getEmail()) 96 | console.log(user2.viewProfile()) 97 | console.log(user2.getType()) 98 | 99 | 100 | class AdminUser extends User { 101 | constructor(name, email) { 102 | super(name, email) 103 | this._type = "Admin" 104 | } 105 | 106 | getType() { 107 | return this._type 108 | } 109 | 110 | // Additional action for the user 111 | addProduct(productName) { 112 | return `Adding product ${productName} as an admin` 113 | } 114 | } 115 | 116 | let admin1 = new AdminUser("jerry doe", "jerrydoe@gmail.com") 117 | console.log(admin1.getName()) 118 | console.log(admin1.getEmail()) 119 | console.log(admin1.viewProfile()) 120 | console.log(admin1.getType()) 121 | console.log(admin1.addProduct("Meat Pie")) 122 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | See the class-file directory to access the class notes --------------------------------------------------------------------------------