├── .vscode
└── settings.json
├── 0_variables.js
├── 10_localstorage.js
├── 1_datatypes.js
├── 2_concat_coercion.js
├── 3_expressions.js
├── 4_loops.js
├── 5_functions.js
├── 6_arrays.js
├── 7_strings.js
├── 8_maths.js
├── 9_date_time.js
├── API
├── index.html
├── index.js
├── markdown.md
├── pract.js
└── style.css
├── advancedJS
├── dom
│ ├── event-delegation.html
│ ├── event-propagation.html
│ ├── project.html
│ └── style.css
└── functions
│ ├── async-await.html
│ ├── callback-hell.js
│ ├── error-handling.html
│ ├── index.html
│ ├── index.js
│ ├── promises.html
│ ├── promises.js
│ └── style.css
├── ecmascripts
├── es2015.js
├── es2016.js
├── es2017.js
├── es2018.js
├── es2019.js
├── es2020.js
├── es2021.js
├── es2022.js
└── es2023.js
├── how_js_works
├── call_stack.html
├── closure.js
├── hoisting.js
├── index.js
├── scope.html
├── scope.js
└── sync_vs_async.js
├── index.html
├── intro.js
├── objects
├── bonus.js
└── index.js
├── timeBasedEvents
├── index.html
├── index.js
├── project.html
└── style.css
└── windows
├── bom
├── index.html
└── index.js
├── dom
├── domCrud.html
├── domSearching.html
├── index.html
└── index.js
└── style.css
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "editor.defaultFormatter": "esbenp.prettier-vscode"
3 | }
4 |
--------------------------------------------------------------------------------
/0_variables.js:
--------------------------------------------------------------------------------
1 | //* ====================================
2 | //* Values and Variable in JavaScript
3 | //* ====================================
4 |
5 | //* In JavaScript, values and variables are fundamental concepts that form the basis of programming.
6 |
7 | //* Values: A value is a piece of information that a program can work with. It can be a number, text, true/false, or more complex data.
8 |
9 | //* Variables: A variable is a container that holds a value. It has a name and can be used to store and manipulate data in a program.
10 |
11 | // console.log("welcome to best js course ");
12 |
13 | // var myAge = 30;
14 | // console.log(myAge);
15 |
16 | //! Let's test
17 | var my_firstName = "John";
18 | //? Explanation: This is a valid variable name. It starts with a letter, and the subsequent characters include letters, numbers, and an underscore. Follows JavaScript naming rules.
19 |
20 | var _myLastName$ = "Doe";
21 | //? Explanation: This is a valid variable name. It starts with an underscore, and the subsequent characters include letters, numbers, and a dollar sign. Follows JavaScript naming rules.
22 |
23 | var 123myAge = 25;
24 | //? Explanation: This is not a valid variable name. It starts with a number, which is not allowed as per JavaScript naming rules. Variable names cannot begin with a digit.
25 |
26 | var $cityName = "New York";
27 | //? Explanation: This is a valid variable name. It starts with a dollar sign, and the subsequent characters include letters. Follows JavaScript naming rules.
28 |
29 | var my@Email = "john@example.com";
30 | //? Explanation: This is not a valid variable name. It includes the special character '@', which is not allowed in JavaScript variable names. Only letters, numbers, underscores, and dollar signs are allowed.
31 |
--------------------------------------------------------------------------------
/10_localstorage.js:
--------------------------------------------------------------------------------
1 | //* ==============================
2 | //* LocalStorage
3 | //* ==============================
4 |
5 | //? The localStorage object allows you to save key/value pairs in the browser.
6 |
7 | // How to add the data from localStorage
8 | localStorage.setItem("youtubeJsCourse", "addingData");
9 |
10 | // How to get the data from localStorage
11 | localStorage.getItem("youtubeJsCourse");
12 |
13 | // How to remove the data from localStorage
14 | localStorage.removeItem("youtubeJsCourse");
15 |
16 | //todo Local Storage can only store strings, so when you want to store a complex data structure like an array or an object, you need to convert it to a string using JSON.stringify:
17 |
18 | //* JSON.stringify: Converts a JavaScript object into a JSON string.
19 | // Useful when you want to send data to a server or store it in a text file, as JSON is a common data interchange format.
20 | // const data = { name: "Vinod", age: 30, city: "pune" };
21 | // const jsonString = JSON.stringify(data);
22 | // console.log(jsonString);
23 | // Output: '{"name":"Vinod","age":30,"city":"pune"}'
24 |
25 | //* JSON.parse: Converts a JSON string into a JavaScript object.
26 | // Useful when you receive JSON data from a server or read it from a file, and you want to work with it as a JavaScript object.
27 |
28 | const jsonString = '{"name":"Vinod","age":30,"city":"pune"}';
29 | const parsedData = JSON.parse(jsonString);
30 | console.log(parsedData);
31 | // Output: { name: 'Vinod', age: 30, city: 'pune' }
32 |
--------------------------------------------------------------------------------
/1_datatypes.js:
--------------------------------------------------------------------------------
1 | //* ============================
2 | //* Data Types Section
3 | //* ============================
4 |
5 | //* Data types define the type of values that a variable can hold.
6 |
7 | //? Types of Primitive Data types
8 |
9 | //? Number: Represents numeric values, including integers and floating-point numbers.
10 | // Example:
11 | // var myFavNum = -5;
12 | // console.log(myFavNum);
13 |
14 | //? String: Represents a sequence of characters enclosed in single or double quotes.
15 | // Example:
16 | // var myName = 'vinod';
17 | // console.log(myName);
18 |
19 | //? Boolean: Represents a logical entity with two values: true or false.
20 | // Example:
21 | // var isRaining = false;
22 | // var areYouAwesome = true;
23 | // console.log(isRaining);
24 |
25 | //? undefined: Represents the absence of a value or an uninitialized variable.
26 | // Example:
27 | // var vinod;
28 | // console.log(vinod);
29 |
30 | //? Null: Represents the absence of a value. It is often used to explicitly indicate that a variable or object property has no assigned value.
31 | // Example:
32 | // var badMemories = null;
33 | // console.log(badMemories);
34 |
35 | //? BigInt: Represents integers of arbitrary precision (available since ECMAScript 2020).
36 | // Example:
37 | // const bigNumber = 1234567890123456789012345678901234567890n;
38 |
39 | //? Symbol: Represents a unique and immutable data type, often used to create unique identifiers.
40 | // Example:
41 | // const mySymbol = Symbol("description");
42 |
43 | //! ============================
44 | //! Data Types Interview Questions
45 | //! ============================
46 |
47 | //? 1: What is the difference between null and undefined in JavaScript❓
48 |
49 | // null: Imagine an Empty Box
50 | // //* Explanation: Think of a variable as a box. When we say a box has null inside, it's like having an empty box. The box exists, but there's nothing valuable or meaningful inside it.
51 |
52 | // //? Example: You have a toy box, but if it's null, it means there are no toys inside. It's not that the box is broken; it just doesn't have anything interesting in it right now.
53 |
54 | // undefined: Imagine a Box That Wasn't Opened Yet
55 | //* Explanation: Now, if we talk about undefined, it's like having a box that you haven't opened yet. You know the box is there, but you haven't put anything inside or looked to see what's in it.
56 |
57 | //? Example: You have a gift box, and until you open it, you don't know what's inside. Right now, it's undefined because you haven't checked or filled it with anything yet.
58 |
59 | // Putting It Together
60 | // Summary: So, null is like having an empty box on purpose, and undefined is like having a box you haven't opened yet. Both tell us that there's nothing meaningful or known inside, but they imply different reasons why.
61 |
62 | //todo Real-life Comparison: If you have an empty lunchbox (null), it means you decided not to put any food in it. If you have a closed lunchbox (undefined), it means you haven't checked or filled it yet.
63 |
64 | //? 2: What is the purpose of typeof operator in JavaScript❓
65 |
66 | // var myName = 1;
67 | // console.log(myName);
68 | // console.log(typeof myName);
69 |
70 | //? 3: What is the result of `typeof null` in JavaScript❓
71 | // var badMemories = null;
72 | // console.log(badMemories);
73 | // console.log(typeof null);
74 |
75 | //? 4: What are primitive data types in JavaScript❓
76 |
77 | //? 5: Convert a string to a number?
78 | // We just need to add the '+' sign before the string
79 | // Example:
80 | // var myFavNum = "10";
81 | // console.log(typeof +myFavNum);
82 | // console.log(typeof Number(myFavNum));
83 |
84 | //? 6: Convert a number to a string?
85 | // We just need to add an empty string after the number
86 | // Example:
87 |
88 | // var str = 5;
89 | // console.log(typeof str);
90 |
91 | //? 7: Explain the concept of truthy and falsy values in JavaScript. Provide examples.❓
92 | //* In JavaScript, values are either considered "truthy" or "falsy" when evaluated in a boolean context.
93 |
94 | //? Truthy values are treated as true when used in conditions. Examples include:
95 | // 👉 true
96 | // 👉 Any non-empty string ("hello")
97 | // 👉 Any non-zero number (42)
98 | // 👉 Arrays and objects, even if they're not empty
99 |
100 | // Falsy values are treated as false in boolean contexts. Examples include:
101 | // 👉 false
102 | // 👉 0 (zero)
103 | // 👉 '' (an empty string)
104 | // 👉 null
105 | // 👉 undefined
106 | // 👉 NaN (Not a Number)
107 |
108 | //? 8: To check if a non-empty string is truthy or falsy in JavaScript, we can directly use if statement.
109 |
110 | // var myName = -5;
111 | // if (true) {
112 | // console.log("this is truthy value");
113 | // } else {
114 | // console.log("its a falsy value");
115 | // }
116 |
117 | //* ========== Data Types End Section ==========
118 |
119 | //todo ---------------- todo Bonus ----------------------
120 |
121 | //* ========== parseInt & parseFloat Section ==========
122 | //? parseInt and parseFloat are both functions in JavaScript used for converting strings to numbers, but they have different use cases.
123 |
124 | //* parseInt: Definition: parseInt is used to parse a string and convert it to an integer (whole number).
125 | // const myString = "42";
126 | // const myNumber = parseInt(myString);
127 | // console.log(myNumber); // Output: 42
128 |
129 | // const myString = "42.5";
130 | // const myNumber = parseInt(myString);
131 | // console.log(myNumber); // Output: 42
132 |
133 | //* parseFloat: Definition: parseFloat is used to parse a string and convert it to a floating-point number (decimal number).
134 | // const myString = "42.5";
135 | // const myNumber = parseFloat(myString);
136 | // console.log(myNumber); // Output: 42.5
137 |
138 | //TODO Key Differences:
139 | //? parseInt is used for converting to integers and ignores anything after the decimal point.
140 | //? parseFloat is used for converting to floating-point numbers, preserving the decimal part.
141 | //? Both functions will attempt to convert as much of the string as possible until an invalid character is encountered.
142 |
143 | //! Here are more examples
144 | // console.log(parseInt("123"));
145 | // // 123 (default base-10)
146 | // console.log(parseInt("123", 10));
147 | // // 123 (explicitly specify base-10)
148 | // console.log(parseInt(" 123 "));
149 | // // 123 (whitespace is ignored)
150 | // console.log(parseInt("077"));
151 | // console.log(parseFloat("077"));
152 | // // 77 (leading zeros are ignored)
153 | // console.log(parseInt("1.9"));
154 | // +console.log(parseFloat("1.9"));
155 | // 1 (decimal part is truncated)
156 |
157 | //! When we will not get an Output
158 | // console.log(parseInt("&123"));
159 | // console.log(parseInt("-123"));
160 | // console.log(parseInt("xyz"));
161 | // NaN (input can't be converted to an integer)
162 |
163 | //? What is the purpose of the NaN value in JavaScript❓
164 | //? NaN stands for "Not a Number" and is returned when a mathematical operation doesn't yield a valid number.
165 | //? Also, to check whether a value is number or not we can use isNaN() function.
166 |
167 | // console.log(isNaN("vinod"));
168 | // console.log(parseInt("xyz"));
169 | // console.log(parseInt("@#$"));
170 |
171 | // //! NaN === NaN, Why is it false ❓
172 | // if (NaN == NaN) {
173 | // console.log("both are equal ");
174 | // } else {
175 | // console.log("not equal");
176 | // }
177 |
178 | //* ========== parseInt & parseFloat End Section ==========
179 |
--------------------------------------------------------------------------------
/2_concat_coercion.js:
--------------------------------------------------------------------------------
1 | //* ============================
2 | //* Data Types Section - part 2
3 | //* ============================
4 |
5 | //* Concatenation in JavaScript
6 | //? In JavaScript, the + sign is not only used for arithmetic addition but also for string concatenation. When the + operator is used with strings, it concatenates the strings together.
7 | //? It's important to note that if any operand of the + operator is a string, JavaScript will treat the other operands as strings as well, resulting in string concatenation. If both operands are numbers, the + operator performs numeric addition.
8 |
9 | // const str = "Hello " + "World";
10 | // console.log(str);
11 |
12 | //* Type coercion is the automatic conversion of "values" from one data type to another.
13 | //? It is a fundamental part of JavaScript and can be used to make code more readable and efficient.
14 | //? There are two types of coercion in JavaScript: implicit and explicit. Implicit coercion happens automatically, while explicit coercion is done manually by the programmer.
15 | //! It's worth noting that type coercion can lead to unexpected results, so it's essential to be aware of how JavaScript handles these situations.
16 |
17 | // let sum = "5" + 10;
18 | // console.log(sum);
19 |
20 | //* ============================
21 | //* Tricky Interview Questions
22 | //* ============================
23 | // console.log(10 + "20");
24 | // console.log(9 - "5");
25 | // console.log("Java" + "Script");
26 | // console.log(" " + " ");
27 | // let sum = " " + 0;
28 | // console.log(typeof sum);
29 | // console.log("vinod" - "thapa");
30 | // console.log(true + true);
31 | // console.log(true + false);
32 | // console.log(false + true);
33 | // console.log(false - true);
34 |
--------------------------------------------------------------------------------
/3_expressions.js:
--------------------------------------------------------------------------------
1 | //* ===================================
2 | //* EXPRESSIONS AND OPERATORS Section
3 | //* ====================================
4 |
5 | //? 1st we will see what is expression means and also what is operand and operator in any expression?
6 |
7 | //* Types of Operators in JS
8 | // Assignment operators
9 | // Arithmetic operators
10 | // In arithmetic we increment and decrement operator.
11 | // Comparison operators
12 | // Logical operators
13 | // String operators
14 | // Conditional (ternary) operator
15 |
16 | //* ===================================
17 | //* 1: Assignment operators
18 | //* ====================================
19 |
20 | //? Assignment operators in programming are symbols used to assign values to variables. They take the value on the right side of the operator and assign it to the variable on the left side.
21 |
22 | // examples
23 | // var myFavNum = 15;
24 | // Assigns the value 15 to the variable myFavNum
25 | // var channelName = 'thapa tecnical'
26 |
27 | //* ===================================
28 | //* 2: Arithmetic operators
29 | //* ====================================
30 |
31 | //? Arithmetic operators in programming perform basic mathematical operations on variables or values. They include addition, subtraction, multiplication, division, and modulus.
32 |
33 | //? Addition (+): Adds two values or variables.
34 | // Example:
35 | // var x = 5;
36 | // var y = 10;
37 | // var sum = x + y;
38 | // console.log(sum);
39 |
40 | //? Subtraction (-): Subtracts the right operand from the left operand.
41 | // Example:
42 | // var a = 10;
43 | // var b = 7;
44 | // var difference = a - b;
45 | // console.log(difference);
46 |
47 | //? Multiplication (*): Multiplies two values or variables.
48 | // Example:
49 | // var p = 4;
50 | // var q = 6;
51 | // var product = p * q;
52 | // console.log(product);
53 |
54 | //? Division (/): Divides the left operand by the right operand.
55 | // Example:
56 | // var m = 15;
57 | // var n = 3;
58 | // var quotient = m / n;
59 | // console.log(quotient);
60 |
61 | //? Modulus (%): Returns the remainder when the left operand is divided by the right operand.
62 | // Example:
63 | // var c = 17;
64 | // var d = 5;
65 | // var remainder = c % d;
66 | // console.log(remainder);
67 |
68 | //* ===================================
69 | //* Challenge Time
70 | //* ====================================
71 |
72 | //! What will be the Output 🤔💭
73 | // var result = "hello" / 2 ❓
74 | // var result = "hello" / 2;
75 | // console.log(result);
76 |
77 | //* ===================================
78 | //* InterView Question
79 | //* ====================================
80 |
81 | //! var result = 0.1 + 0.2 ❓ 🤔💭
82 | // var result = 0.1 + 0.2;
83 | // console.log(result.toFixed(2));
84 | // when working with floating-point numbers in JavaScript, consider using methods like toFixed() when precise decimal representation is necessary.
85 |
86 | // const result = 55 * "hello" ❓
87 | // var result = 55 * "hello";
88 | // console.log(result);
89 |
90 | //* ===================================
91 | //* 3: String Operators
92 | //* ====================================
93 |
94 | //? There are a few ways to concatenate strings in JavaScript. The most common way is to use the + operator. For example, to concatenate the strings "Hello" and "World", you would use the following code:
95 |
96 | // var str1 = "Hello";
97 | // var str2 = "World ";
98 | // var str3 = str1 + Str2;
99 | // console.log(str3);
100 |
101 | //* ===================================
102 | //* InterView Question
103 | //* ====================================
104 |
105 | //! console.log("5" + 3); // Outputs "53" ❓
106 |
107 | //* ===================================
108 | //* 4: comparison operators
109 | //* ====================================
110 |
111 | //? Comparison operators in JavaScript are used to compare values and return a Boolean result (true or false).
112 |
113 | //? Equal (==): Checks if two values are equal, performing type coercion if necessary.
114 | // console.log(5 == "5");
115 |
116 | //? Strict Equal (===):
117 | // Checks if two values are equal without performing type coercion.
118 | // console.log(5 === "5");
119 |
120 | //? Not Equal (!= 👉 ! =):
121 | // Checks if two values are not equal, performing type coercion if necessary.
122 | // console.log(5 != 5);
123 |
124 | //? Greater Than (>):
125 | // Checks if the value on the left is greater than the value on the right.
126 | // Example: 10 > 5 evaluates to true.
127 | // console.log(5 > 2);
128 |
129 | //? Less Than (<):
130 | // Checks if the value on the left is less than the value on the right.
131 | // Example: 5 < 10 evaluates to true.
132 | // console.log(5 < 10);
133 |
134 | //? Greater Than or Equal To (>=):
135 | // Checks if the value on the left is greater than or equal to the value on the right.
136 | // Example: 10 >= 10 evaluates to true.
137 | // console.log(10 <= 10);
138 |
139 | //? Less Than or Equal To (<=):
140 | // Checks if the value on the left is less than or equal to the value on the right.
141 | // Example: 5 <= 10 evaluates to true.
142 | // console.log(5 >= 10);
143 |
144 | //* ===================================
145 | //* InterView Question
146 | //* ====================================
147 |
148 | //! What is the difference between == and === operators in JavaScript❓
149 | //? The equality == operator is a comparison operator that compares two values and returns true if they are equal. The strict equality === operator is also a comparison operator, but it compares two values and returns true only if they are equal and of the same type.
150 | // ex.
151 | // let num1 = 1;
152 | // let num2 = "1";
153 |
154 | // if (num1 === num2) {
155 | // console.log("equal");
156 | // } else {
157 | // console.log("not equal");
158 | // }
159 |
160 | //* ===================================
161 | //* 5: Logical operators in JavaScript
162 | //* ====================================
163 |
164 | //* There are three main logical operators: && (logical AND), || (logical OR), and ! (logical NOT).
165 |
166 | //? Logical AND (&&): Returns true if both operands are true, otherwise, it returns false.
167 | // Example:
168 | // var x = 5;
169 | // var y = 10;
170 | // console.log(x > 0 && y < 0);
171 |
172 | //? Logical OR (||): Returns true if at least one of the operands is true, otherwise, it returns false.
173 | // Example:
174 | // var a = 15;
175 | // var b = 0;
176 | // console.log(a > 10 || b > 10);
177 |
178 | //? Logical NOT (!):
179 | //? Returns true if the operand is false, and false if the operand is true.
180 | // Example:
181 | // var isOpen = false;
182 | // console.log(!isOpen);
183 |
184 | //* ===================================
185 | //* InterView Question
186 | //* ====================================
187 |
188 | //? Combining logical operators allows you to create complex conditions:
189 | //! Q: Write a program that determines if a person is eligible to drive based on their age being greater than or equal to 18 and having a valid driver's license❓
190 |
191 | // var age = 19;
192 | // var hadDrivingLicense = false;
193 |
194 | // // age > 18
195 | // // age == 18
196 | // console.log(age >= 18 && hadDrivingLicense);
197 |
198 | //! How would the result change if hasDriverLicense was set to false❓
199 |
200 | //* ===================================
201 | //* 6: Unary operator
202 | //* ====================================
203 | //? Unary operators in JavaScript are operators that work with only one operand. They perform various operations such as negation, incrementing, decrementing, type conversion, and more.
204 |
205 | //? Unary Plus (+): Converts its operand into a number. If the operand is not already a number, it attempts to convert it.
206 | // console.log(+3);
207 | // console.log(+"5");
208 |
209 | //? Unary Negation (-): Negates its operand, converting non-numbers into numbers and then negating them.
210 | // console.log(-5);
211 | // console.log(-"3");
212 |
213 | //? Prefix Increment (++x) and Prefix Decrement (--x): In prefix form, the value of the operand is first incremented or decremented, and then the result is returned.
214 | // var x = 5;
215 | // var y = --x;
216 | // console.log(y);
217 | // console.log(x);
218 |
219 | //? Postfix Increment (x++) and Postfix Decrement (x--): In postfix form, the value of the operand is first returned, and then it is incremented or decremented.
220 | // var x = 5;
221 | // var y = x++;
222 | // console.log(y);
223 | // console.log(x);
224 |
225 | //todo The current value of x (which is 5) is assigned to y. After the assignment, the value of x is then incremented by 1.
226 |
227 | //* ===================================
228 | //* 7: Conditional (ternary) operator
229 | //* ====================================
230 |
231 | //? syntax: condition ? expressionIfTrue : expressionIfFalse;
232 |
233 | // ! write a program to check if the candidates isEligibleForDrive or not? Age must be equal to or greater then 18.
234 |
235 | // var age = 19;
236 | // var result = age >= 18 ? "Yes" : "No";
237 | // console.log(result);
238 |
239 | //! Q: Let say you have a variable score representing a student's exam score. If the score is greater than or equal to 60, the student passes; otherwise, they fail. Use the conditional (ternary) operator to determine the result and store it in a variable called result. Log the result to the console❓
240 |
241 | // var score = 99;
242 | // var result = score >= 60 ? "Pass" : "Fail";
243 | // console.log(result);
244 |
245 | //* ===================================
246 | //* Combined Interview Questions
247 | //* ====================================
248 |
249 | // console.log(typeof ("5" - 3));
250 |
251 | // console.log(2 < 12 < 5);
252 |
253 | // console.log("20" + 10 + 10);
254 |
--------------------------------------------------------------------------------
/4_loops.js:
--------------------------------------------------------------------------------
1 | //* ===============================
2 | //* Conditional statement Section
3 | //* ===============================
4 |
5 | //* ===============================
6 | //* If Statement
7 | //* ===============================
8 |
9 | //? If Else: The if...else statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement in the optional else clause will be executed.
10 |
11 | //? Syntax
12 | // if (condition) {
13 | // // Code to be executed if the condition is true
14 | // } else {
15 | // // Code to be executed if the condition is false
16 | // }
17 |
18 | //? Let check the temperature
19 | // var temperature = 25;
20 | // if (temperature > 30) {
21 | // console.log("lets go to beach");
22 | // } else {
23 | // console.log("tv dekhte hai yr");
24 | // }
25 |
26 | //? We can also use an else if clause to check additional conditions:
27 | // var temperature = 15;
28 | // if (temperature >= 30) {
29 | // console.log("lets go to beach");
30 | // } else if (temperature >= 20 && temperature < 30) {
31 | // console.log("tv dekhte hai yr");
32 | // } else {
33 | // console.log("kambhal oodo so jawo");
34 | // }
35 |
36 | //* ===============================
37 | //* Interview Question
38 | //* ===============================
39 |
40 | //! Requirements:
41 | //? If the person is 18 years or older, a citizen, and registered to vote, display a message saying they are eligible to vote.
42 | //? If the person is younger than 18, not a citizen, or not registered to vote, display a message saying they are not eligible to vote.
43 | //? If the person is 18 or older but not a citizen, display a message saying they are not eligible due to citizenship status.
44 | //? If the person is 18 or older, a citizen, but not registered to vote, display a message saying they are not eligible due to registration status.
45 | //? Extended voting eligibility checker with additional conditions
46 |
47 | // Assume the user's age, citizenship status, and registration status as inputs
48 | // let userAge = 19;
49 | // let isCitizen = true; // Assume true for citizen, false for non-citizen
50 | // let isRegistered = true; // Assume false for not registered, true for registered
51 | // //! Check eligibility using if...else statements with multiple conditions
52 |
53 | // if (userAge >= 18) {
54 | // if (isCitizen) {
55 | // if (isRegistered) {
56 | // console.log("You are eligible to vote");
57 | // } else {
58 | // console.log("You are not eligible due to registration status");
59 | // }
60 | // } else {
61 | // console.log("you are not eligible due to citizenship status");
62 | // }
63 | // } else {
64 | // console.log("You are not eligible to vote (Younger)");
65 | // }
66 |
67 | //* ===============================
68 | //* Interview Questions
69 | //* ===============================
70 | //! 1: Write a program to check if a number is even or odd.
71 | var num = "7";
72 | if (num % 2 === 0) {
73 | console.log("Num is even");
74 | } else {
75 | console.log("Num is odd");
76 | }
77 |
78 | //! 2: Write a program to check if a number is prime.
79 | //todo Prime numbers are numbers that have only 2 factors: 1 and themselves.
80 | //? All prime numbers greater than 2 are odd.
81 | //? However, not all odd numbers are prime.
82 |
83 | var num = 13;
84 | var isPrime = true;
85 |
86 | for (var i = 2; i < num; i++) {
87 | if (num % i === 0) {
88 | isPrime = false;
89 | break;
90 | }
91 | }
92 |
93 | if (isPrime) {
94 | console.log("Num is prime");
95 | } else {
96 | console.log("Num is not prime");
97 | }
98 |
99 | //! 3: Write a program to check if a number is positive, negative, or zero.
100 | var num = -10;
101 | if (num === 0) {
102 | console.log("NUm is zero");
103 | } else if (num > 0) {
104 | console.log("NUm is positive ");
105 | } else {
106 | console.log("NUm is negative ");
107 | }
108 |
109 | //* ===============================
110 | //* Switch Statement
111 | //* ===============================
112 |
113 | //? Switch Statement: The switch statement is used to perform different actions based on different conditions.
114 | //? Syntax:
115 | // switch (expression) {
116 | // case value1:
117 | // // Code to be executed if expression === value1
118 | // break;
119 |
120 | // case value2:
121 | // // Code to be executed if expression === value2
122 | // break;
123 |
124 | // // More cases can be added as needed
125 |
126 | // default:
127 | // // Code to be executed if none of the cases match
128 | // }
129 |
130 | //todo let's see the example
131 | //! Explain how the switch statement works and what will be the output when the variable day is set to different values.
132 |
133 | // var day = "Friday";
134 |
135 | // switch (day) {
136 | // case "Monday":
137 | // console.log("today is monday");
138 | // break;
139 |
140 | // case "Friday":
141 | // console.log("omg lets have party today");
142 | // break;
143 |
144 | // case "Sunday":
145 | // console.log("Lets go to movie");
146 | // break;
147 |
148 | // default:
149 | // console.log("no condition match");
150 | // }
151 |
152 | //?=========================
153 | // ? Challenge time
154 | //? ==========================
155 |
156 | //! Write a JavaScript switch statement that takes a variable areaOfShapes representing different shapes, and based on its value, calculates and logs the area of the corresponding shape. Consider three shapes: 'Rectangle,' 'Circle,' and 'Square.' For 'Rectangle,' use variables a and b as the sides; for 'Circle,' use a variable r as the radius; and for 'Square,' use variable a as the side length. If the provided shape is not recognized, log a message saying, 'Sorry the shape is not available.' Test your switch statement with areaOfShapes set to 'Square' and sides a and b set to 5 and 10, respectively. Ensure that the correct area (25 in this case) is logged to the console.
157 |
158 | // var areaOfShapes = "square";
159 | // var a = 5;
160 | // var b = 10;
161 | // var result;
162 | // switch (areaOfShapes) {
163 | // case "square":
164 | // result = a * a;
165 | // console.log(result);
166 | // break;
167 |
168 | // case "rectangle":
169 | // result = a * b;
170 | // console.log(result);
171 | // break;
172 |
173 | // case "circle":
174 | // var r = 2;
175 | // result = 3.142 * (r * r);
176 | // console.log(result);
177 | // break;
178 |
179 | // default:
180 | // console.log("No shape matches");
181 | // }
182 |
183 | //! Question: Explain the purpose of the code. What is it calculating based on the values of areaOfShapes, a, and b?
184 | //? The code calculates and logs the area of different shapes (rectangle, circle, square) based on the value of the areaOfShapes variable.
185 |
186 | //! Question: What will be the output if areaOfShapes is set to "Square" and why?
187 | //? The output will be the square of the variable a (25) since the case matches "Square."
188 |
189 | //! Question: Why is there a break statement after each case in the switch statement?
190 | //? The break statement is used to exit the switch statement after the corresponding case is executed, preventing fall-through to subsequent cases.
191 |
192 | //! Question: If areaOfShapes is set to "Circle," what will be logged to the console, and why is the variable r defined within the case block?
193 | //? The output will be the area of a circle with radius r (28.26) since the case matches "Circle," and r is defined within the case block.
194 |
195 | //! Question: What will happen if areaOfShapes is set to a shape that is not covered by any of the existing case statements?
196 | //? The default case logs "Sorry, the shape is not available" if areaOfShapes is set to a shape not covered by any existing case.
197 |
198 | //! Question: How does the switch statement handle the flow of control based on the value of areaOfShapes?
199 | //? The switch statement evaluates the value of areaOfShapes and executes the code block corresponding to the matching case. The break statements ensure that only the relevant code block is executed.
200 |
201 | //* ===============================
202 | //* While Loop
203 | //* ===============================
204 |
205 | // ? While Loop: A while loop in JavaScript is a control structure that repeatedly executes a block of code as long as a specified condition remains true. The loop continues iterating while the condition is true, and it terminates when the condition becomes false.
206 |
207 | // while (condition) {
208 | // // Code to be executed as long as the condition is true
209 | // }
210 |
211 | //* Simple while loop to count from 1 to 10 🧑💻
212 | // var num = 1;
213 | // while (num <= 10) {
214 | // console.log(num);
215 | // num++;
216 | // }
217 |
218 | //! practice 🧑💻
219 | //? let's create a table of 5
220 | // 5*1 = 5
221 | // 5*2 = 10
222 | // 5*2 = 10
223 |
224 | // var num = 1;
225 | // while (num <= 10) {
226 | // console.log("5 * " + num + " = " + 5 * num);
227 | // // console.log(`5 * ${num} = ${5 * num}`);
228 | // num++;
229 | // }
230 |
231 | //* ===============================
232 | //* Do-While Loop
233 | //* ===============================
234 |
235 | //? Do...While Loop: A do...while loop in JavaScript is similar to a while loop, but it guarantees that the loop body will be executed at least once before checking the loop condition. The loop continues to execute while the specified condition is true, and it terminates when the condition becomes false.
236 |
237 | // Syntax: do {
238 | // // Code to be executed at least once
239 | // } while (condition);
240 |
241 | //* Simple do...while loop to count from 1 to 10 🧑💻
242 |
243 | // var num = 1;
244 | // while (num <= 10) {
245 | // console.log(num);
246 | // num++;
247 | // }
248 |
249 | // var num = 1;
250 | // do{
251 | // console.log(num);
252 | // num++;
253 | // }while (num <= 10)
254 |
255 | //? Common Use Cases:
256 | //? When you want to guarantee the execution of the loop body at least once.
257 | //? When the number of iterations is not known beforehand, and you want to validate the condition after the first iteration.
258 |
259 | //? Example: Validating User Input with a Do...While Loop(user need to write a valid number) 🧑💻
260 |
261 | // let userInput;
262 | // let positiveNumber;
263 | // do {
264 | // userInput = prompt("enter any positive number");
265 | // positiveNumber = parseFloat(userInput);
266 | // } while (isNaN(positiveNumber) || positiveNumber < 0);
267 | // console.log("You entered a valid positive number:", positiveNumber);
268 |
269 | //* ===============================
270 | //* For Loop
271 | //* ===============================
272 |
273 | //? For Loop: A for loop in JavaScript is a control flow statement that allows you to repeatedly execute a block of code a specified number of times. It's particularly useful when you know the exact number of iterations needed.
274 |
275 | // example: for (initialization; condition; iteration) {
276 | // // Code to be executed in each iteration
277 | // }
278 | // Initialization: Executed before the loop starts. Often used to initialize a counter variable.
279 | // Condition: Evaluated before each iteration. If false, the loop terminates.
280 | // Iteration: Executed after each iteration. Typically used to update the loop control variable.
281 |
282 | //* Simple for loop to count from 1 to 10
283 |
284 | // var num = 1;
285 | // do {
286 | // console.log(num);
287 | // num++;
288 | // } while (num <= 10);
289 |
290 | // for (var num = 1; num <= 10; num++) {
291 | // console.log(num);
292 | // }
293 |
294 | //? Key Point:
295 | // The initialization, condition, and iteration expressions are optional. You can omit any or all of them, but you must include the semicolons.
296 | //* The code for (;;) {} represents an infinite loop in JavaScript. This construct is commonly used when you want a loop to run indefinitely or until a break statement is encountered within the loop. It's equivalent to while (true) {}.
297 |
298 | //* use case: Game Development:
299 | //? In game development, an infinite loop can be used to continuously update and render game frames until a specific condition (e.g., game over) is met.
300 |
301 | // for (;;) {
302 | // // Update game logic and render frames
303 | // }
304 |
305 | //? Common Use Cases:
306 | // When you know the exact number of iterations needed.
307 | // Iterating over elements in an array.
308 | // Performing a task a specific number of times.
309 |
310 | //! practice :
311 | //! Calculate the sum of numbers from 1 to 10 using a for loop 🧑💻
312 |
313 | // var sum = 0;
314 | // debugger;
315 | // for (var num = 1; num <= 10; num++) {
316 | // var sum = sum + num;
317 | // }
318 | // console.log(sum);
319 |
320 | //! Generating a Times Table:🧑💻
321 | //! Example 3: Generating a times table of 5 with a for loop.
322 | // var num = 1;
323 | // while (num <= 10) {
324 | // console.log("5 * " + num + " = " + 5 * num);
325 | // // console.log(`5 * ${num} = ${5 * num}`);
326 | // num++;
327 | // }
328 |
329 | // for (var num = 1; num <= 10; num++) {
330 | // console.log("5 * " + num + " = " + 5 * num);
331 | // }
332 |
333 | //! Homework ➡️ JavaScript program to print table for given number (8,9,12,15) using for Loop?
334 |
335 | //? More Practice
336 | //!1: program To check if a year is a leap year🧑💻
337 | //? If a year is divisible by 4 and not divisible by 100, or
338 | //? If a year is divisible by 400,
339 | // then it is a leap year. Otherwise, it is not a leap year.
340 |
341 | // var year = 2020;
342 |
343 | // if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
344 | // console.log(year, "it's a leap year");
345 | // } else {
346 | // console.log(year, "it's not a leap year");
347 | // }
348 |
349 | //! 2: Drawing Patterns with Asterisks: 🧑💻
350 |
351 | //* i\j 1 2 3 4 5
352 | //* ----------------------------
353 | //* 1 * - - - -
354 | //* 2 * * - - -
355 | //* 3 * * * - -
356 | //* 4 * * * * -
357 | //* 5 * * * * *
358 |
359 | // for (var i = 1; i <= 5; i++) {
360 | // var pattern = "";
361 | // for (var j = 1; j <= i; j++) {
362 | // pattern = pattern + " *";
363 | // }
364 | // console.log(pattern);
365 | // }
366 |
--------------------------------------------------------------------------------
/5_functions.js:
--------------------------------------------------------------------------------
1 | //* ===============================
2 | //* Function in JavaScript
3 | //* ==============================
4 | //? In JavaScript, a function is a block of reusable code that performs a specific task or set of tasks. Functions are used to organize code into modular and manageable pieces, promote code reuse, and make programs more readable.
5 |
6 | // 3 students at a same time wants to find the sum of two numbers
7 | // 1st student
8 | // var a = 5,
9 | // b = 10;
10 | // var sum1 = a + b;
11 | // console.log(sum1);
12 |
13 | // // 2nd student
14 | // var a = 15,
15 | // b = 15;
16 | // var sum2 = a + b;
17 | // console.log(sum2);
18 |
19 | // // 3rd student
20 | // var a = 55,
21 | // b = 15;
22 | // var sum3 = a + b;
23 | // console.log(sum3);
24 |
25 | // lets make a reusable code
26 |
27 | // function sum(a, b) {
28 | // return a + b;
29 | // }
30 |
31 | // console.log(sum(5, 5));
32 | // console.log(sum(15, 50));
33 | // console.log(sum(25, 750));
34 |
35 | //* ===============================
36 | //* Function Declaration:
37 | //* ==============================
38 |
39 | //? Declare a function using the function keyword, followed by the function name, parameters (if any), and the function body.
40 | //? This step defines the function and specifies what code should be executed when the function is called.
41 |
42 | // function greet() {
43 | // console.log("Hello Guys, Welcome to Thapa Technical JS Course ");
44 | // }
45 |
46 | //* =================================================
47 | //* Function Invocation (Calling a Function):
48 | //* =================================================
49 |
50 | //?After declaring a function, you can invoke or call it by using its name followed by parentheses.
51 | //? If the function has parameters, provide values (arguments) for those parameters inside the parentheses.
52 |
53 | //? How to call a function
54 | // greet();
55 |
56 | //! Practice Time
57 | //! 1. Write a function to find the sum of two numbers.
58 |
59 | //todo Tips "1st declare the function & then call it" In JavaScript, it's a good practice to declare (define) your functions before you call them. This ensures that the function is available for use when you try to call it.
60 |
61 | // Function definition
62 | // function sum() {
63 | // var a = 15,
64 | // b = 10;
65 | // console.log(a + b);
66 | // }
67 |
68 | // // Calling the function
69 | // sum();
70 | // sum();
71 | //* ==============================
72 | //* Function Parameter:
73 | //* ==============================
74 |
75 | //? A function parameter is a variable that is listed as a part of a function declaration. It acts as a placeholder for a value that will be provided when the function is called. Parameters allow you to pass information into a function, making it more versatile and reusable.
76 |
77 | // Syntax: function functionName(parameter1, parameter2, ...params) {
78 | // // Function body
79 | // // Code to be executed when the function is called
80 | // }
81 |
82 | //* ==============================
83 | //* Function Argument:
84 | //* ==============================
85 |
86 | //? A function argument is a value that you provide when you call a function. Arguments are passed into a function to fill the parameters defined in the function declaration.
87 |
88 | //? syntax:
89 | //? functionName(argument1, argument2, ...);
90 |
91 | //! Practice Time
92 | //? Let's say we want to greet students with one same line
93 | //! Write a JavaScript program that defines a function called greet to welcome individuals to the Thapa Technical JS Course. The function should take a name parameter and output the message "Hello [name], Welcome to Thapa Technical JS Course". Call the function twice, once with the argument "vinod" and once with the argument "ram".
94 | // function greet(name) {
95 | // console.log("Hello " + name + ", Welcome to Thapa Technical JS Course");
96 | // }
97 |
98 | // greet("ram");
99 | // greet("sita");
100 |
101 | //! 1. Write a function to find the sum of two numbers with parameters.
102 | // function sum(a, b) {
103 | // console.log(a + b);
104 | // }
105 | // // Calling the function
106 | // sum(5, 10);
107 | // sum(50, 10);
108 |
109 | //* ==============================
110 | //* Function expressions
111 | //* ==============================
112 | //? A function expression is a way to define a function as part of an expression. It can be either named or anonymous. If it's named, it becomes a named function expression.
113 |
114 | // var result = function sum(a, b) {
115 | // console.log(a + b);
116 | // };
117 |
118 | // result(10, 15);
119 |
120 | //* ==============================
121 | //* Anonymous Function
122 | //* =============================
123 | //? An anonymous function is a function without a name. It can be created using either a function expression or a function declaration without a specified name.
124 |
125 | // var result = function (a, b) {
126 | // console.log(a + b);
127 | // };
128 |
129 | // result(10, 15);
130 |
131 | //* ==============================
132 | //* Return Keyword
133 | //* =============================
134 | //? Return Keyword: In JavaScript, the return statement is used within a function to specify the value that the function should produce or provide back to the code that called it. The return statement stops the execution of a function and sends a value back to the caller
135 |
136 | //? Syntax
137 | // return expression;
138 |
139 | //! Example 1: Returning a Sum of two number
140 |
141 | // function sum(a, b) {
142 | // // console.log(a + b);
143 | // return a + b;
144 | // console.log("hello I am function");
145 | // }
146 |
147 | // var result = sum(5, 5);
148 | // // console.log(result);
149 |
150 | // console.log("the sum of two number is " + result);
151 |
152 | // console.log(sum(5, 5));
153 | // console.log(sum(15, 50));
154 | // console.log(sum(25, 750));
155 |
156 | //* ==============================
157 | //* IIFE - immediately invoked function expression
158 | //* =============================
159 | //? An IIFE, or Immediately Invoked Function Expression, is a JavaScript function that is defined and executed immediately after its creation. It is a way to create a self-contained block of code that doesn't interfere with the surrounding code and executes immediately
160 |
161 | // Syntax
162 | // (function () {
163 | // // code to be executed
164 | // })();
165 |
166 | // var result = (function (a, b) {
167 | // console.log(a + b);
168 | // return a + b;
169 | // })(5, 10);
170 |
171 | // console.log("the sum of two number is " + result);
172 |
173 | // !Practice Time ( IIFE with Parameters)
174 |
175 | //? Interview Questions
176 |
177 | //! Question 1: Calculator Function
178 | //! Write a JavaScript function calculator that takes two numbers and an operator as parameters and returns the result of the operation. The function should support addition, subtraction, multiplication, and division.
179 |
180 | // console.log(calculator(5, 2, '+')); // Output: 7
181 | // console.log(calculator(8, 4, '-')); // Output: 4
182 | // console.log(calculator(10, 2, '/')); // Output: 5
183 |
184 | // const calculator = (num1, num2, operator) => {
185 | // let result;
186 | // switch (operator) {
187 | // case "+":
188 | // return num1 + num2;
189 |
190 | // case "-":
191 | // result = num1 - num2;
192 | // return result;
193 |
194 | // case "*":
195 | // result = num1 * num2;
196 | // return result;
197 |
198 | // case "/":
199 | // if (num2 === 0) {
200 | // return "0 is not allowed";
201 | // } else {
202 | // result = num1 / num2;
203 | // return result;
204 | // }
205 |
206 | // default:
207 | // return "no operator found";
208 | // }
209 | // };
210 |
211 | // console.log(calculator(5, 2, "+")); // Output: 7
212 | // console.log(calculator(8, 4, "-")); // Output: 4
213 | // console.log(calculator(10, 0, "/")); // Output: 5
214 |
215 | //! Reverse a String:
216 | //! Write a function to reverse a given string without using built-in reverse methods.
217 |
218 | const isReverse = (str) => {
219 | let reverse = "";
220 | for (let char = str.length - 1; char >= 0; char--) {
221 | reverse = reverse + str[char];
222 | }
223 | return reverse;
224 | };
225 |
226 | console.log(isReverse("vinod thapa"));
227 |
228 | //! Palindrome Check:
229 | //! Create a function to determine if a given string is a palindrome (reads the same backward as forward).
230 |
231 | // // isi isi
232 | // radar
233 | // level
234 | const isPalindrome = (str) => {
235 | let reverse = "";
236 | for (let char = str.length - 1; char >= 0; char--) {
237 | reverse = reverse + str[char];
238 | }
239 | // if (str === reverse) {
240 | // return true;
241 | // } else {
242 | // return false;
243 | // }
244 |
245 | return str === reverse ? true : false;
246 | };
247 |
248 | console.log(isPalindrome("level"));
249 |
--------------------------------------------------------------------------------
/7_strings.js:
--------------------------------------------------------------------------------
1 | //* =========================================
2 | //* String in JavaScript
3 | //* =========================================
4 |
5 | //? Strings in JavaScript are a fundamental data type that represents a sequence of characters.
6 |
7 | // Note:
8 | //? Strings created with single or double quotes works the same.
9 | // There is no difference between the two.
10 |
11 | //* String Properties:
12 | //? length: Property that returns the length of the string (number of characters).
13 |
14 | // const str = "Hello, World!";
15 | // console.log(str.length);
16 | // including space n all
17 |
18 | //* =========================================
19 | //* Escape Character
20 | //* =========================================
21 |
22 | //? Escape Character: In JavaScript, the backslash \ is used as an escape character. It allows you to include special characters in a string.
23 |
24 | // Code Result Description
25 | // \' ' Single quote
26 | // \" " Double quote
27 | // \\ \ Backslash
28 |
29 | // let text = "My name is " Thapa Technical " & I am a Full Stack Developer. ";
30 | // let text =
31 | // "My name is ' Thapa Technical ' & \\ I am a \"Full Stack \" Developer. ";
32 | // // let text = 'My name is " Thapa Technical " & I am a Full Stack Developer. ';
33 |
34 | // console.log(text);
35 |
36 | //* =========================================
37 | //* String Search Methods
38 | //* =========================================
39 |
40 | //? 2: String Search Methods
41 | //? a: indexOf(): The indexOf() method returns the index (position) of the first occurrence of a string in a string, or it returns -1 if the string is not found:
42 | // syntax
43 | // indexOf(searchString)
44 | // indexOf(searchString, position)
45 |
46 | // let text = "Vinod Thapa";
47 | // console.log(text.indexOf("thapa"));
48 | // The indexOf() method is case sensitive.
49 | // console.log(text.indexOf("Thapa"));
50 |
51 | // let strArr = Array.from(text);
52 | // // console.log(strArr);
53 | // let strMap = strArr.map((curElem, index) => `${curElem} - ${index}`);
54 | // console.log(strMap);
55 |
56 | //? b: lastIndexOf() : The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
57 | // syntax
58 | // lastIndexOf(searchString)
59 | // lastIndexOf(searchString, position)
60 |
61 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
62 | // let index = text.indexOf("JavaScript");
63 | // let index = text.lastIndexOf("JavaScript");
64 | // let index = text.lastIndexOf("JavaScript", 40);
65 | // console.log(index);
66 |
67 | //? c: search(): The search() method searches a string for a string (or a regular expression) and returns the position of the match.
68 | //* Returns the index number where the first match is found. Returns -1 if no match is found.
69 |
70 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
71 | // let result = text.search(/Javascript/i);
72 | // console.log(result);
73 |
74 | //*👉 Important Tips
75 | // The search() method cannot take a second start position argument.
76 | // The indexOf() method cannot take powerful search values (regular expressions).
77 | // They accept the same arguments (parameters), and return the same value
78 |
79 | //? match() : Returns an array of the matched values or null if no match is found.
80 |
81 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
82 | // let result = text.match("Javascript");
83 | // let result = text.match("JavaScript");
84 | //todo here the js converts the normal text into regular expression text.match(/JavaScript/); without the g flag
85 | // let result = text.match(/Javascript/gi);
86 |
87 | // console.log(result);
88 |
89 | //? matchAll() : Returns an iterator of all matches, providing detailed information about each match. Returns an empty iterator if no match is found.
90 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
91 | // let matchResult = text.matchAll("javascript");
92 | // let matchResult = text.matchAll("JavaScript");
93 | //todo here the js converts the normal text into regular expression text.match(/JavaScript/g); also adds the g flag at the end
94 |
95 | // console.log(...matchResult);
96 |
97 | // for (let item of matchResult) {
98 | // console.log(item[0]);
99 | // }
100 |
101 | // for (let index of matchResult) {
102 | // console.log(index.index);
103 | // }
104 |
105 | // for (let { index } of matchResult) {
106 | // console.log(index);
107 | // }
108 |
109 | //? includes(): Returns true if the string contains the specified value, and false otherwise.
110 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
111 | // let includeResult = text.includes(/java/i);
112 | // let includeResult = text.includes("J");
113 | // console.log(includeResult);
114 |
115 | // Note: includes() is case sensitive. includes() is an ES6 feature.
116 |
117 | //? startsWith(): The startsWith() method returns true if a string begins with a specified value.Otherwise it returns false:
118 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
119 | // let result = text.startsWith("Helcome");
120 | // let result = text.startsWith("Hello");
121 | // console.log(result);
122 |
123 | //* start position for the search can be specified
124 | // let result = text.startsWith("welcome", 18);
125 | // let result = text.startsWith("welcome", 17);
126 | // console.log(result);
127 |
128 | //? endsWith(): The endsWith() method returns true if a string ends with a specified value. Otherwise it returns false:
129 |
130 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
131 | // let result = text.endsWith("welcome");
132 | // let result = text.endsWith("course");
133 | // console.log(result);
134 |
135 | //* =========================================
136 | //* Extracting String Parts:
137 | //* =========================================
138 | //! Extracting String Parts:
139 |
140 | //? String.prototype.substr() it is deprecated ❌
141 |
142 | //? a: slice() extracts a part of a string and returns the extracted part in a new string.
143 | // syntax
144 | // slice(start, end);
145 |
146 | // Todo JavaScript counts positions from zero.
147 | //? First position is 0. Second position is 1.
148 |
149 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
150 | // let result = text.slice(6);
151 | // let result = text.slice(6, 15);
152 | // console.log(result);
153 |
154 | // subString() substring()
155 |
156 | //? a: substring: Extracts a portion of the string based on starting and ending indices.
157 | //* camelCase is used to separate words, substring is not to be intended as Sub String but as Substring
158 | // syntax
159 | // substring(indexStart) // index starts with 0
160 | // substring(indexStart, indexEnd)
161 |
162 | //* substring() is similar to slice(). The difference is that start and end values less than 0 are treated as 0 in substring().
163 |
164 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
165 | // let result = text.slice(-6);
166 | // console.log(result);
167 |
168 | //! Homework
169 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
170 | // let result = text.substring(0);
171 | // let result = text.substring(1);
172 | // let result = text.substring(-5);
173 | // console.log(result);
174 |
175 | //! similarities
176 | //todo In both the slice() and substring() methods, the end parameter indicates the ending index up to which the extraction occurs, but the character at the end index is excluded from the extracted substring.
177 |
178 | //* =========================================
179 | //* Interview Question
180 | //* =========================================
181 | //! What is the output for the following code?
182 |
183 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
184 | // let result = text.slice(1);
185 | // let result = text.replace("H", "");
186 | // let result = text.substring(1);
187 | //? Optional
188 | // let result = text.replace("JavaScript", "Vinod");
189 | // let result = text.replaceAll("JavaScript", "Vinod");
190 |
191 | // console.log(result);
192 |
193 | //* =========================================
194 | //* Extracting String Characters
195 | //* =========================================
196 | //! Extracting String Characters
197 | // There are 3 methods for extracting string characters:
198 |
199 | //? The charAt(position) Method
200 | //? The charCodeAt(position) Method
201 | //? The at(position) Method
202 |
203 | //? charAT() : The charAt() method returns the character at a specified index (position) in a string
204 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
205 | // let result = text.charAt(6);
206 | // let result = text.charAt(-6);
207 | // console.log(result);
208 |
209 | //? charCodeAt() : The charCodeAt() method returns the code of the character at a specified index in a string. The method returns a UTF-16 code (an integer between 0 and 65535).
210 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
211 | // let result = text.charCodeAt(6);
212 | // console.log(result);
213 |
214 | //todo ES2022 introduced the string method at():
215 | //? The at() method returns the character at a specified index (position) in a string. The at() method returns the same as carAt().
216 | // let text = "Hello JavaScript, welcome to our world best JavaScript course";
217 | // let result = text.at(-6);
218 | // console.log(result);
219 |
220 | //todo Note
221 | // The at() method is a new addition to JavaScript.
222 | // It allows the use of negative indexes while charAt() do not.
223 | // Now you can use myString.at(-2) instead of charAt(myString.length-2).
224 |
225 | //* =========================================
226 | //* Replacing String Content:
227 | //* =========================================
228 | //! Replacing String Content:
229 | //? replace() : The replace method is used to replace a specified value with another value.
230 | // const str = "Hello, World!";
231 | // const newStr = str.replace("World", "JavaScript");
232 | // console.log(newStr); // Outputs: Hello, JavaScript!
233 |
234 | //? Case-Insensitive Replacement: To perform a case-insensitive replacement, you can use the i flag in the regular expression.
235 | // let originalString = "Hello, World! How are you, World?";
236 | // let replacedString = originalString.replace(/world/gi, "vinod");
237 | // console.log(replacedString);
238 |
239 | //* =========================================
240 | //* Other Useful Methods:
241 | //* =========================================
242 |
243 | //! Other Useful Methods:
244 | //? toUpperCase and toLowerCase: Converts the string to uppercase or lowercase.
245 | // const str = "JavaScript";
246 | // console.log(str.toUpperCase()); // Outputs: JAVASCRIPT
247 | // console.log(str.toLowerCase()); // Outputs: javascript
248 |
249 | //? trim: Removes whitespace from both ends of the string.
250 | // const str = " Hello, World! ";
251 | // console.log(str.length);
252 |
253 | // let trimStr = str.trim();
254 | // console.log(trimStr);
255 | // console.log(trimStr.length);
256 |
257 | //? split: Splits the string into an array of substrings based on a specified delimiter.
258 | // const str = "apple,orange,banana";
259 | // let strArr = str.split(",").reverse().join();
260 | // console.log(strArr);
261 |
262 | //* =========================================
263 | //* //! Interview Questions
264 | //* =========================================
265 |
266 | //! 1: Write a JavaScript function that prints the letters 'a' through 'z' in the console. You should use a loop to iterate through the letters and print each one on a new line.
267 |
268 | // console.log("a".charCodeAt(0));
269 | // console.log("z".charCodeAt(0));
270 |
271 | // for (let char = 97; char <= 122; char++) {
272 | // console.log(String.fromCharCode(char));
273 | // }
274 |
275 | //! 2: Write a function to count the number of vowels in a string?
276 |
277 | // const countVowels = (str) => {
278 | // const vowels = "aeiou";
279 | // let count = 0;
280 | // for (let char of str) {
281 | // console.log(char);
282 | // // console.log(str.includes(char));
283 | // if (vowels.includes(char)) {
284 | // count++;
285 | // }
286 | // }
287 | // return count;
288 | // };
289 | // console.log(checkAllVowelPresentOrNot("my name u is vinod @ thapa"));
290 | // console.log(countVowels("Hello a i o u world"));
291 |
292 | //! 3: Write a function to check if all the vowels presents in a string or not?
293 |
294 | // const checkAllVowelPresentOrNot = (str) => {
295 | // const vowels = "aeiou";
296 | // for (let char of vowels) {
297 | // // console.log(char);
298 | // // console.log(str.includes(char));
299 | // if (!str.includes(char)) {
300 | // return false;
301 | // }
302 | // }
303 | // return true;
304 | // };
305 |
306 | // console.log(checkAllVowelPresentOrNot("my name u is vinod @ thapa"));
307 |
308 | //! 4: Write a JavaScript function to check if the given sting is Pangram or not?
309 |
310 | const pangramChecker = (str) => {
311 | let inputArr = str.toLowerCase().split("");
312 | // console.log(inputArr);
313 | // // console.log("z".charCodeAt());
314 | const values = inputArr.filter(
315 | (curElem) =>
316 | curElem.charCodeAt() >= "a".charCodeAt() &&
317 | curElem.charCodeAt() <= "z".charCodeAt()
318 | );
319 | // console.log(values);
320 |
321 | return new Set(values).size === 26;
322 |
323 | // return [...new Set(values)].length === 26;
324 | };
325 |
326 | console.log(pangramChecker("The quick @ brown fox jumps ove the lazy dog"));
327 |
--------------------------------------------------------------------------------
/8_maths.js:
--------------------------------------------------------------------------------
1 | //* =========================================
2 | //* Math Object in JavaScript
3 | //* =========================================
4 |
5 | //* Math: The Math namespace object contains static properties and methods for mathematical constants and functions.
6 | //* Math works with the Number type. It doesn't work with BigInt.
7 |
8 | //? 1: Constants:
9 | //* - Math.PI: Represents the mathematical constant Pi (π).
10 | // const piValue = Math.PI;
11 | // console.log(piValue);
12 |
13 | //* =========================================
14 | //* 2. Basic Operations:
15 | //* =========================================
16 |
17 | //? Math.abs(): The Math.abs() static method returns the absolute value of a number.
18 | // or in simple, how far the number is from 0. It will be always positive
19 |
20 | // console.log(Math.abs(5));
21 | // console.log(Math.abs(-115));
22 |
23 | //? Math.round(x): Rounds a number to the nearest integer.
24 | // const roundedValue = Math.round(3.7);
25 | // console.log(roundedValue);
26 |
27 | //? Math.ceil(x): Returns the value of x rounded up to its nearest integer:
28 | // const ceilValue = Math.ceil(3.7);
29 | // console.log(ceilValue);
30 |
31 | //? Math.floor(x): Returns the value of x rounded down to its nearest integer.
32 | // const floorValue = Math.floor(3.7);
33 | // console.log(floorValue);
34 |
35 | //? Math.trunc(x): Returns the integer part of x:
36 | // const truncValue = Math.trunc(3.7);
37 | // console.log(truncValue);
38 |
39 | //todo Math.trunc() and Math.sign() were added to JavaScript 2015 - ES6.
40 | // const truncValue = Math.trunc(-3.7);
41 | // const floorValue = Math.floor(-3.1);
42 | // console.log(truncValue);
43 | // console.log(floorValue);
44 |
45 | //todo Notes:
46 | // No matter how many chars are there after decimal, they all will always return only number before the decimal.
47 | // round rounds to the nearest integer.
48 | // floor always rounds down.
49 | // ceil always rounds up.
50 |
51 | //* =========================================
52 | //* 3. Exponential and Logarithmic Functions:
53 | //* =========================================
54 |
55 | //? Math.pow(x, y): Returns the value of x to the power of y.
56 | // console.log(Math.pow(2, 5));
57 | // console.log(2 ** 5);
58 |
59 | //? Math.sqrt(): Math.sqrt(x) returns the square root of x:
60 | // let squareRoot = Math.sqrt(25);
61 | // console.log(squareRoot);
62 |
63 | //? Math.log(x) returns the natural logarithm of x.
64 | // let logResult = Math.log(1);
65 | // let logResult = Math.log(2);
66 | // console.log(logResult);
67 |
68 | //? Math.log2(x) returns the base 2 logarithm of x.
69 | // let logResult = Math.log2(8);
70 | // console.log(logResult);
71 |
72 | //* =========================================
73 | //* Interview Question
74 | //* =========================================
75 |
76 | //! Generate Random number
77 | //? Math.random(): Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)
78 |
79 | console.log((Math.random() * 100).toFixed(3));
80 |
--------------------------------------------------------------------------------
/9_date_time.js:
--------------------------------------------------------------------------------
1 | //* =========================================
2 | //* Date & Time Objects in JavaScript
3 | //* =========================================
4 |
5 | //? Date() constructor: The Date() constructor creates Date objects. When called as a function, it returns a string representing the current time.
6 |
7 | //? Creating a Date Object:
8 | // You can create a new Date object using the new keyword. It can be done in several ways:
9 | //todo There are 9 ways to create a new date object:
10 |
11 | // Syntax
12 | // new Date()
13 | // new Date(date string)
14 |
15 | // new Date(year,month)
16 | // new Date(year,month,day)
17 | // new Date(year,month,day,hours)
18 | // new Date(year,month,day,hours,minutes)
19 | // new Date(year,month,day,hours,minutes,seconds)
20 | // new Date(year,month,day,hours,minutes,seconds,ms)
21 |
22 | // new Date(milliseconds)
23 |
24 | //? Current date and time
25 | //? new Date(): Creates a Date object representing the current date and time.
26 | // const currentDate = new Date();
27 | // console.log(currentDate);
28 | //todo This is the ISO 8601 format, which is a standard for representing dates and times. In this format, the date and time are represented together, separated by the letter "T". The "Z" at the end indicates that the time is in UTC (Coordinated Universal Time).
29 |
30 | // But the same when you run on browser it will return more human-readable format.
31 |
32 | //? 2: new Date(dateString): Creates a Date object based on the provided date string.
33 | // const dateString = "2024-02-19T10:44:09.274Z";
34 | // const dateFromString = new Date(dateString);
35 | // console.log(dateFromString);
36 |
37 | //? 3: new Date(year, month): Creates a Date object with the specified year and month.
38 | // const date1 = new Date(2025, 12);
39 | // console.log(date1);
40 |
41 | //? 4: new Date(year, month, day): Creates a Date object with the specified year, month, and day.
42 | // const date2 = new Date(2024, 1, 19);
43 | // console.log(date2);
44 |
45 | //? 5: new Date(year, month, day, hours): Creates a Date object with the specified year, month, day, and hours.
46 | // const date3 = new Date(2024, 1, 19, 10);
47 | // console.log(date3);
48 |
49 | //? 6: new Date(year, month, day, hours, minutes): Creates a Date object with the specified year, month, day, hours, and minutes.
50 | // const date4 = new Date(2024, 1, 19, 10, 44);
51 | // console.log(date4);
52 |
53 | //? 7: new Date(year, month, day, hours, minutes, seconds): Creates a Date object with the specified year, month, day, hours, minutes, and seconds.
54 | // const date5 = new Date(2024, 1, 19, 10, 44, 9);
55 | // console.log(date5);
56 |
57 | //? 8: new Date(year, month, day, hours, minutes, seconds, ms): Creates a Date object with the specified year, month, day, hours, minutes, seconds, and milliseconds.
58 | // const date6 = new Date(2024, 1, 19, 10, 44, 9, 274);
59 | // console.log(date6);
60 |
61 | //? 9: new Date(milliseconds): Creates a Date object representing the number of milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC).
62 | // const curMilliSeconds = new Date().getTime();
63 | // // const milliseconds = 1632090690883; // Example milliseconds
64 | // const dateFromMilliseconds = new Date(curMilliSeconds);
65 | // console.log(dateFromMilliseconds);
66 |
67 | //todo Note:
68 | //? 1: JavaScript counts months from 0 to 11:
69 | // ?January = 0, December = 11
70 |
71 | //? 2: JavaScript Stores Dates as Milliseconds: JavaScript stores dates as number of milliseconds since January 01, 1970.
72 |
73 | //* Date String Format: If the dateString is in a recognizable format, the Date object will be created accordingly.
74 | //? new Date(date string) creates a date object from a date string
75 | // const date1 = new Date("2024-01-05"); // Year-Month-Day
76 | // const date2 = new Date("January 5, 2024"); // Month Day, Year
77 | // console.log(date1);
78 | // console.log(date2);
79 |
80 | //* ==================================================
81 | //* JavaScript Get Date Methods / Getting Components:
82 | //* ===================================================
83 |
84 | // You can get various components of a date using the methods of the Date object:
85 | // const currentDate = new Date();
86 | // //? In a date object, the time is static.
87 | // const year = currentDate.getFullYear();
88 | // const month = currentDate.getMonth(); // 0-based index
89 | // const date = currentDate.getDate();
90 | // const day = currentDate.getDay();
91 | // console.log(currentDate);
92 | // console.log(day);
93 | // In JavaScript, the first day of the week (day 0) is Sunday.
94 | // day of the week (0 for Sunday, 1 for Monday, ..., 6 for Saturday)
95 |
96 | //* ==================================================
97 | //* JavaScript Set Date Methods / Setting Components:
98 | //* ===================================================
99 |
100 | // const date = new Date();
101 |
102 | //? setFullYear(yearValue[, monthValue[, dayValue]]): Sets the full year for a specified date according to local time.
103 | // console.log(date);
104 |
105 | // date.setFullYear(2025);
106 | // console.log(date); // Date object with the year set to 2025
107 |
108 | //? setMonth(monthValue[, dayValue]): Sets the month for a specified date according to local time.
109 | // date.setMonth(5); // June (months are zero-based)
110 | // console.log(date); // Date object with the month set to June
111 |
112 | //? setDate(dayValue): Sets the day of the month for a specified date according to local time.
113 | // date.setDate(15);
114 | // console.log(date); // Date object with the day of the month set to 15
115 |
116 | //* ==================================================
117 | //* JavaScript Get Time Methods / Getting Components:
118 | //* ===================================================
119 | // const currentTime = new Date();
120 |
121 | // const hours = currentTime.getHours();
122 | // const minutes = currentTime.getMinutes();
123 | // const seconds = currentTime.getSeconds();
124 | // const time = currentTime.getTime();
125 | // console.log(time);
126 |
127 | //* ==================================================
128 | //* JavaScript Set Time Methods / Getting Components:
129 | //* ===================================================
130 |
131 | // const date = new Date();
132 |
133 | //? setHours(hourValue[, minuteValue[, secondValue[, millisecondValue]]]): Sets the hours for a specified date according to local time.
134 | // date.setHours(10);
135 | // console.log(date); // Date object with the hours set to 10
136 |
137 | //? setMinutes(minuteValue[, secondValue[, millisecondValue]]): Sets the minutes for a specified date according to local time.
138 | // date.setMinutes(30);
139 | // console.log(date); // Date object with the minutes set to 30
140 |
141 | //? setSeconds(secondValue[, millisecondValue]): Sets the seconds for a specified date according to local time.
142 | // date.setSeconds(45);
143 | // console.log(date); // Date object with the seconds set to 45
144 |
145 | //? setMilliseconds(millisecondValue): Sets the milliseconds for a specified date according to local time.
146 | // const date = new Date();
147 |
148 | // date.setMilliseconds(500);
149 | // console.log(date); // Date object with the milliseconds set to 500
150 |
151 | //? setTime(timeValue): Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.
152 | // const date = new Date();
153 | // date.setTime(1832090690883);
154 | // console.log(date); // Date object representing the specified time
155 |
156 | //* ================================================================
157 | //* A few useful methods of the Date object in JavaScript
158 | //* ================================================================
159 |
160 | //? 1: toLocaleString(): Returns a string representing the date and time portion of a Date object using the current locale's conventions.
161 | // const date = new Date();
162 | // const localString = date.toLocaleString();
163 | // console.log(localString); // Example output: "2/19/2024, 4:30:00 PM" (depending on the locale)
164 |
165 | //? 2: toLocaleDateString(): Returns a string representing the date portion of a Date object using the current locale's conventions.
166 | // const date = new Date();
167 | // const localDateString = date.toLocaleDateString();
168 | // console.log(localDateString); // Example output: "2/19/2024" (depending on the locale)
169 |
170 | //? 3: toLocaleTimeString(): Returns a string representing the time portion of a Date object using the current locale's conventions.
171 | // const date = new Date();
172 | // const localTimeString = date.toLocaleTimeString();
173 | // console.log(localTimeString); // Example output: "4:30:00 PM" (depending on the locale)
174 |
175 | //? 5: parse(): Parses a string representation of a date and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
176 | // const dateString = "2024-02-19T16:30:00Z";
177 | // const parsedDate = Date.parse(dateString);
178 | // console.log(parsedDate); // Example output: 1703254200000 (milliseconds)
179 |
180 | //* ==================
181 | //* //* Bonus
182 | //* =================
183 |
184 | // let newDate = new Date();
185 | // console.log(Date.now());
186 | // console.log(newDate.getTime());
187 |
188 | //? Date.now() is a static method of the Date object.
189 | //? Use Date.now() if you want the timestamp right this second.
190 | //? It returns the current timestamp (number of milliseconds) representing the current moment.
191 | //? Use new Date().getTime() if you have an existing Date object from elsewhere and want its timestamp.
192 |
193 | //! ==================
194 | //! Interview Questions
195 | //! =================
196 |
197 | //! 1: Write a function to add a specified number of days to a given date.
198 |
199 | // const addDaysToDate = (date, extraDay) => {
200 | // // console.log(date);
201 | // // console.log(date.setDate(date.getDate() + extraDay));
202 | // // console.log(new Date(1709769600000));
203 | // let updatedDate = date.setDate(date.getDate() + extraDay);
204 | // return new Date(updatedDate);
205 | // };
206 |
207 | // // Example usage:
208 | // const date = new Date("2024-02-29");
209 | // const newDate = addDaysToDate(date, 7);
210 | // console.log(newDate);
211 | // console.log(newDate.toLocaleDateString());
212 |
213 | //! Question: Write a function to calculate the difference in days between two given dates.
214 |
215 | // const getDaysDifference = (d1, d2) => {
216 | // let oneDay = 24 * 60 * 60 * 1000;
217 | // let diff = Math.abs(d1 - d2);
218 | // return Math.round(diff / oneDay);
219 | // };
220 |
221 | // // Example usage:
222 | // const date1 = new Date("2024-02-19");
223 | // const date2 = new Date("2024-03-01");
224 | // console.log(getDaysDifference(date1, date2)); // Output: 11 (difference in days)
225 |
--------------------------------------------------------------------------------
/API/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
22 |
23 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/advancedJS/functions/callback-hell.js:
--------------------------------------------------------------------------------
1 | //* ================================
2 | //* Callback hell
3 | //* ================================
4 |
5 | //? Callback hell, also known as the Pyramid of Doom, refers to a situation in asynchronous JavaScript programming where multiple nested callbacks are used to handle asynchronous operations. This often results in code that is difficult to read, understand, and maintain due to its deeply nested structure.
6 |
7 | const getStudentData = () => {
8 | setTimeout(() => {
9 | console.log("Hi, My name is vinod");
10 | setTimeout(() => {
11 | console.log("Hi, My middleName is Bahadur");
12 | setTimeout(() => {
13 | console.log("Hi, My lastName is Thapa");
14 | setTimeout(() => {
15 | console.log("Hi, I like to code ");
16 | setTimeout(() => {
17 | console.log("Hi, I live in pune");
18 | setTimeout(() => {
19 | console.log("Hi, I was born in Pokhara, Nepal");
20 | setTimeout(() => {
21 | console.log("Hi, I love to play football");
22 | setTimeout(() => {
23 | console.log("Hi,I was a national Player in athletics ");
24 | }, 1000);
25 | }, 1000);
26 | }, 1000);
27 | }, 1000);
28 | }, 1000);
29 | }, 1000);
30 | }, 1000);
31 | }, 1000);
32 | };
33 |
34 | getStudentData();
35 |
--------------------------------------------------------------------------------
/advancedJS/functions/error-handling.html:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 | Dad Jokes
15 |
16 |
33 |
34 |
35 |
36 |
Welcome to Dad Jokes!
37 |
38 |
39 |
40 |
41 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/advancedJS/functions/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
12 |
13 |
14 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/advancedJS/functions/index.js:
--------------------------------------------------------------------------------
1 | //* ---------------------------------------------------
2 | //* First-Class Function - it's just a concept
3 | //* ---------------------------------------------------
4 | // A language feature where functions are treated as first-class citizens.
5 | // Functions can be assigned to variables, passed as arguments to other functions, and returned from other functions.
6 | //? A "first-class function" means that functions can be treated as values, assigned to variables, and passed around as arguments.
7 |
8 | // // Function declaration
9 | // function sayHello(name) {
10 | // return "Hello, " + name + "!";
11 | // }
12 |
13 | // // // Assigning the function to a variable
14 | // var greetFunction = sayHello;
15 |
16 | // // // Using the variable as a function
17 | // console.log(greetFunction("Thapa"));
18 |
19 | //* -------------------------------
20 | //* Higher-Order Functions:
21 | //* -------------------------------
22 | //? Definition: A higher-order function is a function that takes one or more functions as arguments or returns a function as a result.
23 |
24 | //* -------------------------------
25 | //* Callback Functions:
26 | //* -------------------------------
27 | //? Definition: A callback function is a function passed as an argument to another function and is executed after the completion of a task.
28 |
29 | //* Here is the example ✅
30 | // Callback function
31 | // function processUserInput(name, greetUser) {
32 | // console.log("Received input: " + name);
33 | // greetUser(name);
34 | // }
35 |
36 | // // Function to be used as a callback
37 | // function greetUser(name) {
38 | // console.log(`Hello! ${name}`);
39 | // }
40 |
41 | // processUserInput("Vinod", greetUser);
42 |
43 | // processUserInput is a higher-order function because it takes another function (callback) as an argument.
44 | // greetUser is a callback function because it's passed as an argument to processUserInput and gets executed after the completion of the main task
45 |
46 | //* -------------------------------
47 | //* Closure:
48 | //* -------------------------------
49 |
50 | //? A closure is created when an inner function has access to the variables of its outer function, even after the outer function has finished executing.
51 |
52 | // function multiplier(factor) {
53 | // return function (number) {
54 | // console.log(number, factor);
55 | // return number * factor;
56 | // };
57 | // }
58 |
59 | // const double = multiplier(2);
60 | // console.log(double(5));
61 |
62 | //* also one more example
63 | // function outerFunction() {
64 | // var outerVariable = "I'm from outer";
65 |
66 | // function innerFunction() {
67 | // console.log(outerVariable);
68 | // }
69 |
70 | // return innerFunction;
71 | // }
72 |
73 | // var closureFunction = outerFunction();
74 | // closureFunction(); // Outputs: "I'm from outer"
75 |
76 | // Here when we are calling the closureFunction() it is actually going to call the innerFunction() but in our executionContext the outerFunction is already popped out. Still we can access the outerVaribale value and how we are able to access it, is what closure all about ?
77 |
78 | // We just need to know that an inner function has always access to the variables of the outer (parent) function. That's it.
79 |
80 | // Why is it like that? It's because the variable object of the parent function stays in memory even after the function returns, and our inner function has access to this variable object through the scope chain.
81 |
82 | // It might be beneficial to clarify that the call stack is simply the execution order and it is not the same thing as the computer's memory, which is where the variables are held. So even though the function was removed from the call stack, its variables are still maintained in memory until they are no longer needed and garbage collection comes and removes them.
83 |
84 | //* ===================================
85 | //* Interview Question:
86 | //* ===================================
87 | //! Write a program to perform mathematical operations using callback functions and two variables in JavaScript.
88 |
89 | //? Instructions:
90 | //? Define a higher-order function called mathOperation that takes three arguments: x, y, and operation.
91 | //? Implement two callback functions:
92 | //? add: Takes two numbers x and y and returns their sum.
93 | //? sub: Takes two numbers x and y and returns the result of subtracting x from y.
94 | //? Use the mathOperation function to perform addition and subtraction operations on two variables a and b.
95 | //? Display the results of the operations.
96 |
97 | const mathOperation = (a, b, operation) => {
98 | return operation(a, b);
99 | };
100 |
101 | const add = (a, b) => {
102 | return a + b;
103 | };
104 |
105 | const sub = (a, b) => {
106 | return b - a;
107 | };
108 |
109 | console.log(mathOperation(5, 15, add));
110 | console.log(mathOperation(5, 15, sub));
111 |
--------------------------------------------------------------------------------
/advancedJS/functions/promises.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
11 |
12 |
Welcome to Dad Jokes!
13 |
14 |
15 |
16 |
17 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/advancedJS/functions/promises.js:
--------------------------------------------------------------------------------
1 | //* ==========================================
2 | //* Promise in JavaScript
3 | //* ==========================================
4 |
5 | //? A promise in JavaScript is an object that represents the eventual completion or failure of an asynchronous operation. It allows you to handle asynchronous operations more easily and cleanly by providing a way to write asynchronous code that looks synchronous.
6 |
7 | //todo 👉 In simpler terms, a promise is like a placeholder for the result of an asynchronous operation. Or A container for the future result or value.
8 |
9 | //* It can be in one of three states:
10 |
11 | //? Pending: Initial state, neither fulfilled nor rejected.
12 | //* Fulfilled(Resolved): The operation completed successfully.
13 | //! Rejected: The operation failed or encountered an error.
14 |
15 | //? Promises have built-in methods like then and catch to handle the results of asynchronous operations when they complete or encounter errors, making it easier to write asynchronous code that is more readable and maintainable compared to traditional callback-based approaches.
16 |
17 | //* ==========================================
18 | //* Using the Promise Constructor (Class):
19 | //* ==========================================
20 |
21 | //? You can create a promise using the Promise constructor. This involves creating a new instance of the Promise class, which takes a function as an argument. This function, often referred to as the "executor function," takes two parameters: resolve and reject. You call resolve when the asynchronous operation is successful and reject when it encounters an error.
22 |
23 | //* real life example
24 |
25 | //todo 1: default state is pending
26 |
27 | //todo 2: Promise Made: Your friend promises to call you after 2 days at 6 pm. This is similar to creating a promise in JavaScript.
28 |
29 | //todo 3: Pending Stage: During the 2-day period, you're in a "pending" stage. You're not sure whether your friend will fulfill the promise (call you) or break the promise (not call you). Similarly, when you create a promise in JavaScript, it starts in a pending state until it either resolves (fulfills) or rejects.
30 |
31 | //todo 4: Resolution at a Specific Time: After 2 days and exactly at 6 pm, you'll know whether the promise is fulfilled (resolved) if your friend calls you, or if it's broken (rejected) if your friend doesn't call. This aligns with the idea that promises in JavaScript resolve or reject, often triggered by asynchronous operations, at a specific point in time.
32 |
33 | //* ==========================================
34 | //* 2: Using a Function (Promise Wrapper):
35 | //* ==========================================
36 |
37 | //? You can also create a promise by defining a function that returns a promise. This function usually encapsulates some asynchronous operation. Inside this function, you manually create a promise and resolve or reject it based on the result of the asynchronous operation.
38 |
39 | // syntax
40 | // function myPromiseFunction() {
41 | // return new Promise((resolve, reject) => {
42 | // // Asynchronous operations here
43 | // // If successful, call resolve(value)
44 | // // If there's an error, call reject(error)
45 | // });
46 | // }
47 |
48 | // const pr = new Promise((resolve, reject) => {
49 | // setTimeout(() => {
50 | // reject("Sorry, I can't");
51 | // }, 2000);
52 | // })
53 | // .then((res) => {
54 | // console.log(res);
55 | // })
56 | // .catch((error) => {
57 | // console.log(error);
58 | // })
59 | // .finally(() => {
60 | // console.log("Don't worry, We all miss you and keep smiling");
61 | // });
62 |
63 | // 1: By default promise has the pending state
64 | // 2: the moment we use setTimeout, we need to handle promises, we can do using then and catch
65 |
66 | //* ==========================================
67 | //* Promise Methods
68 | //* ==========================================
69 |
70 | //? Promise.all is used when you want to wait for all promises to complete successfully. Reject state will throw an error.
71 |
72 | //? Promise.allSettled is used when you want to wait for all promises to complete, regardless of success or failure, and get information about their outcomes.
73 |
74 | //? Promise.race is used when you are interested in the result of the first promise that completes, regardless of success or failure.
75 |
76 | // Example usage:
77 |
78 | // The enrollStudent function returns a promise that resolves or rejects based on the success or failure of the enrollment process.
79 | // The then method is used to handle the success case, printing a success message.
80 | // The catch method is used to handle the failure case, printing an error message.
81 | // The finally method is used to print a message indicating the completion of the enrollment process, whether successful or not.
82 |
83 | // Example usage:
84 | // const studentName = "Vinod";
85 |
86 | // const enrollStudent = (studentName) => {
87 | // return new Promise((resolve, reject) => {
88 | // // Simulating asynchronous enrollment process
89 | // setTimeout(() => {
90 | // const isSuccessful = Math.random() > 0.4;
91 |
92 | // if (isSuccessful) {
93 | // resolve(`Enrollment successful for ${studentName}`);
94 | // } else {
95 | // reject(`Enrollment failed for ${studentName}. Please try again.`);
96 | // }
97 | // }, 2000);
98 | // });
99 | // };
100 |
101 | // enrollStudent(studentName)
102 | // .then((res) => {
103 | // console.log(res);
104 | // })
105 | // .catch((err) => {
106 | // console.log(err);
107 | // })
108 | // .finally(() => {
109 | // console.log("Enrollment process completed.");
110 | // });
111 |
112 | const promise1 = new Promise((resolve, reject) =>
113 | setTimeout(() => resolve("First"), 2000)
114 | );
115 |
116 | // const promise2 = new Promise((resolve) =>
117 | // setTimeout(() => resolve("Second"), 5000)
118 | // );
119 |
120 | const promise2 = new Promise((resolve, reject) =>
121 | setTimeout(() => reject("Failed"), 100)
122 | );
123 |
124 | const promise3 = new Promise((resolve) =>
125 | setTimeout(() => resolve("Third"), 1000)
126 | );
127 |
128 | // Promise.all([promise1, promise3, promise2])
129 | // .then((values) => {
130 | // console.log(values);
131 | // })
132 | // .catch((error) => {
133 | // console.error(error);
134 | // });
135 |
136 | // Promise.allSettled([promise1, promise2, promise3])
137 | // .then((values) => {
138 | // console.log(values);
139 | // })
140 | // .catch((error) => {
141 | // console.error(error);
142 | // });
143 |
144 | Promise.race([promise1, promise2, promise3])
145 | .then((values) => {
146 | console.log(values);
147 | })
148 | .catch((error) => {
149 | console.error(error);
150 | });
151 |
--------------------------------------------------------------------------------
/advancedJS/functions/style.css:
--------------------------------------------------------------------------------
1 | * {
2 | margin: 0;
3 | padding: 0;
4 | font-family: "Urbanist", sans-serif;
5 | }
6 |
7 | html {
8 | color: #fff;
9 | font-size: 62.5%;
10 | }
11 |
12 | body {
13 | width: 100%;
14 | height: 100vh;
15 | display: flex;
16 | align-items: center;
17 | justify-content: center;
18 | background-color: #1b1b1d;
19 | }
20 |
21 | .container {
22 | background-color: rgb(255, 255, 255);
23 | text-align: center;
24 | padding: 2.4rem 6.4rem;
25 | border-radius: 0.6rem;
26 | color: #000;
27 | min-width: 32rem;
28 | }
29 |
30 | .api_body {
31 | font-size: 1.7rem;
32 | letter-spacing: 0.1rem;
33 | margin-bottom: 2rem;
34 | margin-top: 1rem;
35 | }
36 |
37 | button {
38 | height: 5rem;
39 | }
40 |
41 | h1 {
42 | font-size: 3.6rem;
43 | }
44 | hr {
45 | margin-bottom: 3.2rem;
46 | }
47 | p,
48 | li,
49 | button {
50 | font-size: 1.7rem;
51 | letter-spacing: 0.1rem;
52 | font-family: "Urbanist", sans-serif;
53 | line-height: 1.6;
54 | }
55 | button {
56 | background-color: #f5ee62;
57 | padding: 0.6rem 2.4rem;
58 | border-radius: 10rem;
59 | margin-right: 3.6rem;
60 | cursor: pointer;
61 | transition: all 0.3s linear;
62 |
63 | &:hover {
64 | box-shadow: inset 0 0 0 0.2rem #f5ee62;
65 | background-color: transparent;
66 | color: #f5ee62;
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/ecmascripts/es2015.js:
--------------------------------------------------------------------------------
1 | //* ======================================
2 | //* Modern JavaScript - EcmaScript 2015
3 | //* =====================================
4 |
5 | //* ======================================
6 | //* LET AND CONST - EcmaScript 2015
7 | //* =====================================
8 |
9 | //? let Keyword: The let keyword is used to declare variables with block scope. Variables declared with let are mutable, meaning their values can be reassigned.
10 |
11 | // var myFavWorldBestName = "vinod Bahadur Thapa";
12 | // myFavWorldBestName = "thapa technical";
13 | // console.log(myFavWorldBestName);
14 |
15 | // let myFavWorldBestName = "vinod Bahadur Thapa";
16 | // myFavWorldBestName = "thapa technical";
17 | // console.log(myFavWorldBestName);
18 |
19 | //? const Keyword: The const keyword is used to declare variables with block scope, but once a value is assigned to a const variable, it cannot be reassigned. const variables are immutable.
20 |
21 | // pi=3.142 * r * r
22 |
23 | // const myFavWorldBestName = "vinod Bahadur Thapa";
24 | // // myFavWorldBestName = "thapa technical";
25 | // console.log(myFavWorldBestName);
26 |
27 | // //? 1st show what var can do
28 | // var name = "thapa";
29 |
30 | // if (true) {
31 | // var name = "vinod";
32 | // console.log(name);
33 | // }
34 |
35 | // name = "technical";
36 | // console.log(name);
37 |
38 | //? ex2: with the help of let keyword
39 | // let name = "thapa";
40 |
41 | // if (true) {
42 | // name = "vinod";
43 | // console.log(name);
44 | // }
45 |
46 | // name = "technical";
47 | // console.log(name);
48 |
49 | //? ex2: with the help of let keyword
50 | // const name = "thapa";
51 |
52 | // if (true) {
53 | // const name = "vinod";
54 | // console.log(name);
55 | // }
56 |
57 | // name = "technical";
58 | // console.log(name);
59 |
60 | // var
61 | // if (true) {
62 | // var name = "vinod";
63 | // console.log(name);
64 | // }
65 | // name = "technical";
66 | // console.log(name);
67 |
68 | // let
69 | // if (true) {
70 | // let name = "vinod";
71 | // console.log(name);
72 | // }
73 | // // name = "technical";
74 | // console.log(name);
75 |
76 | //* ==========================================
77 | //* TEMPLATE STRINGS - EcmaScript 2015
78 | //* =========================================
79 |
80 | //? In ECMAScript 6 (ES6), template strings, also known as template literals, provide a convenient and flexible way to create strings in JavaScript. Template strings are enclosed in backticks (``) rather than single or double quotes.
81 |
82 | // let firstName = "vinod";
83 | // let lastName = "thapa";
84 |
85 | // // Using template string for string interpolation
86 | // let fullName = firstName + lastName;
87 | // let fullName = `${firstName} ${lastName}`;
88 | // console.log(fullName);
89 |
90 | //? String Interpolation: Template strings support string interpolation, allowing you to embed expressions directly within the string. Interpolated expressions are enclosed in ${}
91 |
92 | // let age = 30;
93 |
94 | // // String interpolation with variable
95 | // let message = `I am ${age} years old.`;
96 | // console.log(message);
97 |
98 | // Multi-line Strings: Template strings make it easy to create multi-line strings without the need for concatenation or escape characters.
99 | // let multiLineString = `
100 | // This is a multi-line
101 | // string using template literals.
102 | // It's much cleaner and easier to read.
103 | // `;
104 |
105 | // console.log(multiLineString);
106 |
107 | //? Expression Evaluation: Template expressions can include any valid JavaScript expression.
108 |
109 | //! Practice Time
110 | // console.log("5 * " + num + " = " + 5 * num);
111 | // let num = 5;
112 | // console.log(`5 * ${num} = ${5 * num}`);
113 |
114 | //? Advantages:
115 | //? Readability: Template strings make the code more readable, especially for complex string constructions.
116 |
117 | //? Conciseness: They eliminate the need for explicit string concatenation and reduce the use of escape characters.
118 |
119 | //? Expression Flexibility: Any JavaScript expression can be embedded within ${}.
120 |
121 | //? Multi-line Support: Creating multi-line strings is more straightforward.
122 |
123 | //* ==========================================
124 | //* DEFAULT Parameters
125 | //* =========================================
126 |
127 | //? In ECMAScript 6 (ES6), default parameters were introduced, providing a more concise way to handle function parameter defaults. Default parameters allow you to specify default values for function parameters in the function declaration itself. If a parameter is not provided when the function is called, the default value is used.
128 |
129 | //? Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
130 |
131 | //! Write a function to find sum of two numbers? What if during function call user only passed one argument?
132 |
133 | // function sum(a = 20, myCurClass = 10) {
134 | // return a + b;
135 | // }
136 | // console.log(sum());
137 |
138 | //* ==========================================
139 | //* FAT ARROW FUNCTION
140 | //* =========================================
141 |
142 | //? In ECMAScript 6 (ES6), arrow functions, also known as fat arrow functions, were introduced as a concise way to write anonymous functions.
143 |
144 | // const sum = function (a, b) {
145 | // let result = `The sum of ${a} and ${b} is ${a + b}.`;
146 | // console.log(result);
147 | // };
148 |
149 | // sum(5, 5);
150 |
151 | // const sum = (a, b) => console.log(`The sum of ${a} and ${b} is ${a + b}.`);
152 | // sum(5, 5);
153 |
154 | //! How to convert the same in fat arrow function
155 | // Syntax
156 | // const functionName = (param1, param2, ...) => {
157 | // // Function body
158 | // return result; // Optional
159 | // };
160 |
161 | // todo NOTES
162 |
163 | // //?🚀 1: If the function body consists of a single expression, the braces {} and the return keyword can be omitted.
164 | // const sum = (a, b) => `The sum of ${a} and ${b} is ${a + b}`;
165 | // console.log(sum(5, 5));
166 |
167 | // //? 🚀 2: If there is only one parameter, the parentheses () around the parameter list can be omitted.
168 | // const square = (a) => `The square of ${a} is ${a * a}`;
169 | // console.log(square(5));
170 |
171 | // //? 🚀 3: If there are no parameters, use an empty set of parentheses ().
172 | // const greet = () => console.log("Plz LIKE SHARE & SUBSCRIBE!");
173 | // greet();
174 |
175 | //! ==========================================
176 | //! Part 2 of Modern JavaScript
177 | //! =========================================
178 |
179 | //* =========================================
180 | //* Object Properties - Modern JavaScript
181 | //* =========================================
182 | // const name = "vinod";
183 | // const age = 30;
184 |
185 | //? traditional way
186 | // const person = { name: name, age: age };
187 | //? Using shorthand notation for object property
188 | // const person = { name, age };
189 | // console.log(person);
190 | // Instead of specifying name: name and age: age, you can simply use name and age directly within the object literal, thanks to ES6 shorthand property notation.
191 |
192 | //* ==========================================
193 | //* Destructuring - Modern JavaScript
194 | //* =========================================
195 | //? Destructuring in JavaScript is a way to extract values from arrays or objects and assign them to variables in a concise and readable manner.
196 | //? Use Case: Makes code cleaner and avoids repetitive copying of values.
197 |
198 | //* Destructuring Arrays:
199 | // Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables.
200 |
201 | //? 1: Extracting specific elements:
202 | const numbers = [10, 20, 30];
203 | // const first = numbers[0]; // Traditional way
204 | // const [first, second, third] = numbers;
205 | // console.log(second);
206 |
207 | //? 2: Ignoring elements:
208 | // const [, , third] = numbers;
209 | // console.log(third);
210 |
211 | //! Interview Questions
212 | //! Write a program to swap two variables without using 3rd variable?
213 | let a = 10;
214 | let b = 30;
215 | // a=30, b=10
216 | //? Mostly will do using 3rd var
217 | // let c = b; //c=30
218 | // b = a; // b=10
219 | // a = c; //a=30
220 |
221 | //? without using 3rd variable
222 | // [a, b] = [b, a];
223 | // console.log(a, b);
224 |
225 | //* Destructuring Objects:
226 | const user = { name: "Vinod", age: 30 };
227 | // we will see the real life use of it in our main project of weather app
228 |
229 | //? Extracting properties:
230 | // const myName = user.name; // Traditional way
231 | // const { age, name } = user;
232 | // console.log(age, name);
233 |
234 | //? Renaming properties:
235 | // const { name: fullName, age } = user; // Rename "name" to "fullName"
236 | // console.log(fullName);
237 |
238 | //* ==========================================
239 | //* Spread Operator - Modern JavaScript
240 | //* =========================================
241 | // JavaScript ES6 (ECMAScript 6) introduced the spread operator. The syntax is three dots(...) followed by the array (or iterable*).
242 |
243 | //? 1. Copying an array
244 | // let fruits = ["Apple", "Orange", "mango", "banana"];
245 | // let newFruits = [...fruits];
246 | // console.log(newFruits);
247 |
248 | //? 2: Concatenating arrays / Combining arrays
249 | // const numbers1 = [1, 2, 3, 4];
250 | // const numbers2 = [4, 5, 6];
251 | // const newNumbers = [...numbers1, ...numbers2];
252 | // console.log(newNumbers);
253 |
254 | //? 3: Adding Elements to existing array
255 | // let fruits = ["Apple", "Orange", "mango", "banana"];
256 | // // fruits.push("guava", "grapes");
257 | // fruits.push(...["guava", "grapes"]);
258 | // console.log(fruits);
259 |
260 | //! One more useCases
261 | //? In JavaScript, when you spread a string using the spread syntax (...), it converts the string into an array of its individual characters.
262 |
263 | //? Traditional way
264 | // const country = "INDIA";
265 | // console.log(country.split(""));
266 |
267 | //? New way of doing it
268 | // const country = "INDIA";
269 | // console.log([...country]);
270 |
271 | //* ==========================================
272 | //* Rest parameters - Modern JavaScript
273 | //* =========================================
274 | //? The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a more flexible way to work with functions that can accept varying numbers of arguments.
275 |
276 | //? traditional way of doing it
277 | // const sum = (a, b, c, d) => {
278 | // return a + b + c + d;
279 | // };
280 |
281 | //? with rest parameters
282 | const sum = (a, b, ...numbers) => {
283 | // console.log(typeof numbers);
284 | return numbers.reduce((accum, curVal) => (accum = accum + curVal), 0);
285 | };
286 |
287 | console.log(sum(1, 2, 3, 4));
288 |
289 | //TODO NOTE: A function definition can only have one rest parameter, and the rest parameter must be the last parameter in the function definition.
290 | // function wrong1(...one, ...wrong) {}
291 | // function wrong2(...wrong, arg2, arg3) {}
292 |
--------------------------------------------------------------------------------
/ecmascripts/es2016.js:
--------------------------------------------------------------------------------
1 | //* ==========================================
2 | //* ECMAScript Features (2016):
3 | //* =========================================
4 |
5 | //* ==============================
6 | //* Exponentiation Operator
7 | //* ===============================
8 |
9 | //? ES7 introduces a new mathematical operator called exponentiation operator. This operator is similar to using Math.pow() method. Exponentiation operator is represented by a double asterisk **. The operator can be used only with numeric values.
10 |
11 | //* syntax
12 | // base_value ** exponent_value;
13 |
14 | //? Basic usage:
15 | let base = 2;
16 | let exponent = 3;
17 | console.log("using Math.pow()", Math.pow(base, exponent));
18 | console.log("using exponentiation operator", base ** exponent);
19 |
20 | //? In expressions:
21 | //! calculates the area of a circle with a radius of 5 units.
22 | // let area = Math.PI * 5 ** 2;
23 | // console.log(area.toFixed(2));
24 |
25 | //* ==============================
26 | //* Array.includes()
27 | //* ===============================
28 | //? we have already cover in our world best JS course part-1 at 7:05:01 timeline
29 |
--------------------------------------------------------------------------------
/ecmascripts/es2017.js:
--------------------------------------------------------------------------------
1 | //* ==========================================
2 | //* ECMAScript Features (2017) / ES8
3 | //* =========================================
4 |
5 | //? List of new useful features added in ES8 👇
6 | // String padding
7 | // Object.values()
8 | // Object.entries()
9 | // Trailing commas in function parameter lists and calls
10 | // Async functions
11 |
12 | //* =====================
13 | //* String padding
14 | //* =====================
15 |
16 | //? String padding in JavaScript is a way to add extra characters (like spaces) to a string to make it a specific length.
17 |
18 | //todo Use Case: Makes formatting text easier and more predictable, especially for tables, alignments, and UI elements. No more messy, uneven lines disrupting your visual spells!
19 |
20 | //? Using padStart() to pad from the beginning:
21 | // const companyName = "Kodyfier";
22 | // const paddedName = companyName.padStart(5);
23 | // const paddedName = companyName.padStart(15);
24 | // console.log(paddedName);
25 | // console.log(paddedName.length);
26 |
27 | //? Using padEnd() to pad from the end:
28 | // const paddedName = companyName.padEnd(15);
29 | // const paddedName = companyName.padEnd(15, "$");
30 | // console.log(paddedName);
31 |
32 | //todo Key points:
33 | //? Both padStart() and padEnd() create a new padded string without modifying the original one.
34 |
35 | //? They take two arguments:
36 | //? - targetLength: The total length of the padded string.
37 | //? - padString (optional): The string to use for padding (defaults to spaces).
38 |
39 | //? If the original string is already longer than or equal to targetLength, it's returned as-is.
40 |
41 | //* =====================
42 | //* trailing commas
43 | //* ====================
44 | //? This feature allows to have trailing commas in function declarations, functions calls, array literal & object literal:
45 |
46 | // // Function parameter list
47 | function greet(name, age, boolean) {
48 | console.log(`Hello ${name}, you are ${age} years old.`);
49 | }
50 |
51 | // // Function call
52 | greet("John", 30, true);
53 |
54 | // // Array literal
55 | const colors = ["red", "green", "blue"];
56 |
57 | // // Object literal
58 | // const person = {
59 | // firstName: "John",
60 | // lastName: "Doe",
61 | // age: 30,
62 | // };
63 |
64 | //* ======================================
65 | //* Object.entries() & Object.values()
66 | //* ======================================
67 | //? We have already covered in our Objects Section. Please watch the section for same
68 |
69 | //* ======================================
70 | //* Async Await - Async Functions
71 | //* ======================================
72 | //? We will cover later in the video and you gonna love that part & our final project is based on async await .
73 |
--------------------------------------------------------------------------------
/ecmascripts/es2018.js:
--------------------------------------------------------------------------------
1 | //* ==========================================
2 | //* ECMAScript Features (2018) / ES9
3 | //* =========================================
4 |
5 | //? List of new useful features added in ES8 👇
6 | // Rest/Spread Properties
7 | // Promise.prototype.finally()
8 |
9 | //* ============================
10 | //* Rest/Spread Properties
11 | //* =============================
12 |
13 | //? ES6 introduced the concept of a rest element when working with array destructuring:
14 | // const numbers = [1, 2, 3, 4, 5];
15 | // [first, second, ...others] = numbers;
16 |
17 | // and spread elements:
18 | // const numbers = [1, 2, 3, 4, 5]
19 | // const sum = (a, b, c, d, e) => a + b + c + d + e
20 | // const sumOfNumbers = sum(...numbers)
21 |
22 | //* ES2018 introduces the same but for objects.
23 |
24 | //? Object and Rest Operator
25 | // const student = {
26 | // age: 10,
27 | // name: "vinod",
28 | // isStudent: true,
29 | // };
30 |
31 | // const { age, ...others } = student;
32 | // console.log(others);
33 |
34 | //? Object and Spread operator
35 | // const obj1 = { a: 10, b: 20, c: 50 };
36 | // const obj2 = { c: 30, d: 40 };
37 |
38 | // const newObj = { ...obj2, ...obj1 };
39 | // console.log(newObj);
40 |
41 | //* ============================
42 | //* Promise.finally()
43 | //* =============================
44 | //? We will cover later in our Promises section part of the video and you gonna love that part.
45 |
--------------------------------------------------------------------------------
/ecmascripts/es2019.js:
--------------------------------------------------------------------------------
1 | //* ==========================================
2 | //* ECMAScript Features (2019) / ES10
3 | //* =========================================
4 |
5 | //? List of new useful features added in ES8 👇
6 | // Array.prototype.{flat,flatMap}
7 | // Object.fromEntries()
8 | // String.prototype.{trimStart,trimEnd}
9 | // Symbol.prototype.description
10 | // Optional catch binding
11 |
12 | //* ==================================
13 | //* Array.flat & Array.flatMap
14 | //* ================================
15 | //? flat() is a new array instance method that can create a one-dimensional array from a multidimensional array. (nested arrays into a single, flat array.)
16 |
17 | // const nestedArray = [1, 2, [3, 4], 5];
18 | const nestedArray1 = [1, [2, [3, [4]]], 5];
19 |
20 | // const flattenedArray = nestedArray.flat();
21 | // const flattenedArray = nestedArray1.flat(3);
22 | // console.log(flattenedArray);
23 |
24 | //? flatMap() is a new Array instance method that combines flat() with map(). It’s useful when calling a function that returns an array in the map() callback, but you want your resulted array to be flat:
25 |
26 | // const arr = ["My name", "is vinod", "thapa"];
27 | // const newArr = arr.flatMap((curVal) => curVal.split(" "));
28 | // console.log(newArr);
29 |
30 | //* ============================
31 | //* Object.fromEntries()
32 | //* =============================
33 | //? Objects have an entries() method, since ES2017.
34 | //? It returns an array containing all the object own properties, as an array of [key, value] pairs:
35 |
36 | //? ES2019 introduces a new Object.fromEntries() method, which can create a new object from such array of properties:
37 | // const person = { name: "vinod", age: 30 };
38 | // const entries = Object.entries(person);
39 | // // console.log(entries);
40 |
41 | // const newPerson = Object.fromEntries(entries);
42 | // console.log(newPerson);
43 |
44 | // // // Now Think & let me know Why 🤔,
45 | // console.log(person == newPerson);
46 |
47 | //* ========================================
48 | //* String.prototype.{trimStart,trimEnd}
49 | //* =========================================
50 |
51 | //? trimStart(): Return a new string with removed white space from the start of the original string
52 | // console.log("Testing".trimStart());
53 | // console.log(" Testing".trimStart());
54 | // console.log(" Testing ".trimStart());
55 | // console.log("Testing ".trimStart());
56 |
57 | //? trimEnd(): Return a new string with removed white space from the end of the original string
58 | // console.log("Testing".trimEnd());
59 | // console.log(" Testing".trimEnd());
60 | // console.log(" Testing ".trimEnd());
61 | // console.log("Testing ".trimEnd());
62 |
63 | //* ================================
64 | //* Symbol.prototype.description
65 | //* ===============================
66 |
67 | //? In JavaScript, a Symbol is a primitive data type introduced in ECMAScript 2015 (ES6). It represents a unique identifier that is immutable and guaranteed to be unique. Symbols are often used as property keys in objects to avoid naming conflicts.
68 |
69 | //? The Symbol.prototype.description property is a new feature introduced in ECMAScript 2019 (ES10). It allows you to retrieve the description of a symbol. When you create a symbol, you can optionally provide a description as its parameter. The description property lets you access this description.
70 |
71 | // const mySymbol = Symbol("This is my symbol");
72 | // console.log(typeof mySymbol);
73 | // console.log(mySymbol.description);
74 |
75 | //* ================================
76 | //* Optional catch binding
77 | //* ===============================
78 | //? In ECMAScript 2019 (ES10), a new feature called "optional catch binding" was introduced for the try...catch statement. This feature allows you to omit the parameter in the catch block, making it optional.
79 |
80 | //? We previously had to do: 👇
81 | try {
82 | //...
83 | } catch (e) {
84 | //handle error
85 | }
86 |
87 | //? Now we can omit that optional parameter 👇
88 | try {
89 | 10 + 5;
90 | } catch {
91 | console.log("there is an error");
92 | }
93 |
--------------------------------------------------------------------------------
/ecmascripts/es2020.js:
--------------------------------------------------------------------------------
1 | //* ==========================================
2 | //* ECMAScript Features (2020) / ES11
3 | //* =========================================
4 |
5 | //? List of new useful features added in ES8 👇
6 | // BigInt
7 | // Nullish Coalescing Operator ??
8 | // Optional Chaining Operator ?.
9 | // promise.allSettled
10 |
11 | //* ===================
12 | //* BigInt
13 | //* ================
14 | //? BigInt: BigInt in JavaScript is a data type used to represent and perform operations on large integers that exceed the limits of regular numbers.
15 |
16 | //? Creating BigInts:
17 | //? - Using the `n` suffix:
18 |
19 | // Using the BigInt() constructor:
20 | // const anotherLargeNumber = BigInt("123456789012345678901234567890");
21 | // console.log(anotherLargeNumber);
22 | // console.log(typeof anotherLargeNumber);
23 |
24 | // let maxNumber = Number.MAX_SAFE_INTEGER;
25 | // maxNumber = BigInt(maxNumber);
26 | // let num = maxNumber + 10n;
27 | // console.log(num);
28 |
29 | //* =======================================
30 | //* Nullish Coalescing Operator ??
31 | //* ===================================
32 | //? In JavaScript, the nullish coalescing operator (??) is a logical operator that provides a concise way to handle nullish (null or undefined) values. It returns its right-hand operand when its left-hand operand is null or undefined, otherwise, it returns the left-hand operand.
33 |
34 | // let favNum = 0; // falsy
35 | // // userFavNum = favNum || 10;
36 | // userFavNum = favNum ?? 10;
37 | // console.log(userFavNum);
38 |
39 | //* =======================================
40 | //* Optional Chaining Operator (?.)
41 | //* ===================================
42 | //? It provides a concise way to access properties of an object without worrying about the existence of intermediate properties. It's particularly useful when working with nested objects or accessing properties of objects that may be null or undefined.
43 |
44 | // const person = {
45 | // name: "John",
46 | // address: {
47 | // city: 0,
48 | // zipCode: 12345,
49 | // },
50 | // };
51 |
52 | //? Accessing nested properties without optional chaining
53 | // const city = person.address;
54 | // const city = person.address ? person.address.city : "city is not present";
55 | // console.log(city);
56 |
57 | //? with optional chaining
58 | // const city = person.address?.city ?? "city is not present";
59 | // console.log(city);
60 | //? One more example
61 | // The optional chaining operator can be chained multiple times to access deeply nested properties:
62 |
63 | // const person = {
64 | // name: "John",
65 | // address: {
66 | // city: "New York",
67 | // zipCode: 12345,
68 | // coordinates: {
69 | // latitude: 40.7128,
70 | // longitude: -74.006,
71 | // },
72 | // },
73 | // };
74 |
75 | // // Accessing deeply nested properties with optional chaining
76 | // const latitude = person.address?.coordinates?.latitude ?? "not present";
77 | // console.log(latitude);
78 |
79 | //* =======================================
80 | //* Promise.allSettled()
81 | //* ===================================
82 | //? We will cover later in our Promises section part of the video and you gonna love that part.
83 |
--------------------------------------------------------------------------------
/ecmascripts/es2021.js:
--------------------------------------------------------------------------------
1 | //* ==========================================
2 | //* ECMAScript Features (2021) / ES12
3 | //* =========================================
4 |
5 | //? List of new useful features added in ES8 👇
6 | // String.prototype.replaceAll()
7 | // Logical Assignment Operators (||=, &&=, ??=)
8 | // Numeric Separators
9 | // Promise.any()
10 |
11 | //* ==========================================
12 | //* String.prototype.replaceAll()
13 | //* =========================================
14 | //? replaceAll in JavaScript is a function that replaces all occurrences of a specified value with another value in a given string.
15 |
16 | //? Replacing all occurrences of a word:
17 | // const originalString = "Hello, world! Hello again.";
18 | // const newString = originalString.replaceAll("Hello", "Hi");
19 | // console.log(newString);
20 |
21 | //? Replacing multiple spaces with a single space:
22 | // const text = "This has extra spaces.";
23 | // const normalizedText = text.replaceAll(/\s+/g, " ");
24 | // console.log(normalizedText);
25 |
26 | //* =====================================================
27 | //* Logical Assignment Operators (||=, &&=, ??=)
28 | //* ====================================================
29 |
30 | //? Logical OR-Assignment (||=): This operator assigns the value of its right-hand operand to its left-hand operand if the left-hand operand evaluates to a falsy value (false, null, undefined, 0, '', NaN). Otherwise, it leaves the left-hand operand unchanged.
31 | // let x = false;
32 | // x = x || true; // equivalent to: x = x || true;
33 | // console.log(x); // Output: true
34 |
35 | // let y = 10;
36 | // y ||= 20; // equivalent to: y = y || 20;
37 | // console.log(y); // Output: 10 (unchanged)
38 |
39 | //? Logical AND-Assignment (&&=): This operator assigns the value of its right-hand operand to its left-hand operand if the left-hand operand evaluates to a truthy value. Otherwise, it leaves the left-hand operand unchanged.
40 | // let x = true;
41 | // x &&= false; // equivalent to: x = x && false;
42 | // console.log(x); // Output: false
43 |
44 | let y = 0;
45 | y &&= 20; // equivalent to: y = y && 20;
46 | console.log(y); // Output: 20
47 |
48 | //* ======================
49 | //* Numeric Separators
50 | //* ====================
51 | //? This feature allows underscores (_) to be used as separators within numeric literals to improve readability.
52 | const bigNumber = 1_000_000;
53 | console.log(bigNumber);
54 | // Output: 1000000;
55 |
56 | //* ======================
57 | //* Promise.any()
58 | //* ====================
59 | //? Promise.any(): This method takes an iterable of Promise objects and returns a single Promise that resolves as soon as any of the input Promises fulfill.
60 |
61 | const promise1 = new Promise((resolve, reject) =>
62 | setTimeout(resolve, 200, "Promise 1")
63 | );
64 | const promise2 = new Promise((resolve, reject) =>
65 | setTimeout(reject, 100, "Promise 2")
66 | );
67 | const promise3 = new Promise((resolve, reject) =>
68 | setTimeout(resolve, 300, "Promise 3")
69 | );
70 |
71 | Promise.any([promise1, promise2, promise3]).then((value) => console.log(value));
72 |
73 | //? Difference: while Promise.race() does indeed consider both fulfilled and rejected Promises, Promise.any() only looks for fulfillment among the input Promises. If all input Promises are rejected, Promise.any() will reject with an AggregateError containing all the rejection reasons.
74 |
--------------------------------------------------------------------------------
/ecmascripts/es2022.js:
--------------------------------------------------------------------------------
1 | //* ==========================================
2 | //* ECMAScript Features (2022) / ES13
3 | //* =========================================
4 |
5 | //? List of new useful features added in ES8 👇
6 | // .at() function for indexing
7 | // Object.hasOwn(obj, propKey)
8 |
9 | //* ===============
10 | //* .at()
11 | //* =============
12 | //? Before ES2022, square bracket notation was used to fetch a particular element in an array. This method is straightforward unless you need to perform a backward iteration, i.e., negative indexing. In the case of negative indexing, the common practice was to use arr[arr.length — N], where array length is referred to and indexed from the end.
13 |
14 | //? The .at() method introduced in ES2022 has simplified this process. In a case of positive indexing, .at() will work the same as the square brackets. But for negative indexing, the .at() method allows starting the iteration from the end.
15 |
16 | // const array = [1, 2, 4, 5, 6, 7];
17 | // // console.log(array[array.length - 1]);
18 | // console.log(array.at(-1));
19 |
20 | //todo Note Datatypes supporting this function. 👇
21 | // String
22 | // Array
23 | // All Typed Array classes: Uint8Array etc.
24 |
25 | //* =====================================
26 | //* Object.hasOwn(obj, propKey)
27 | //* =====================================
28 | //? Object.hasOwn() is a static method that you can use to check if a property exists in an object or not. It returns true if the specified object contains the indicated property as its own, and if the property is inherited or doesn’t exist, it returns false. This method takes the object as the first argument and the property you want to check as the second.
29 |
30 | //? Object.hasOwn is the intended alternative for the Object.prototype.hasOwnProperty method. Although Object.prototype.hasOwnProperty has been in JavaScript specification for quite a time, it has some drawbacks.
31 |
32 | const book = {
33 | name: "World Best JS Course",
34 | author: "Thapa Technical",
35 | };
36 |
37 | // // Using Object.prototype.hasOwnProperty() method
38 | // console.log(book.hasOwnProperty("name")); //Output: true
39 | // console.log(book.hasOwnProperty("price")); //Output: false
40 |
41 | // // Using Object.hasOwn method
42 | // console.log(Object.hasOwn(book, "name"));
43 |
44 | //! Issues with hasOwnProperty
45 | //? Issue 01: Doesn't work for objects created using Object.create(null)
46 |
47 | const student = Object.create(null);
48 | console.log(typeof student);
49 | student.name = "vinod";
50 | // console.log(student.hasOwnProperty("name"));
51 | console.log(Object.hasOwn(student, "name"));
52 |
--------------------------------------------------------------------------------
/ecmascripts/es2023.js:
--------------------------------------------------------------------------------
1 | //* ==========================================
2 | //* ECMAScript Features (2022) / ES13
3 | //* =========================================
4 |
5 | //? List of new useful features added in ES8 👇
6 | // Array.findLast()
7 | // Array.findLastIndex()
8 | // Array.prototype.toReversed()
9 | // Array.prototype.toSorted(compareFn)
10 | // Array.prototype.toSpliced(start, deleteCount, ...items)
11 | // Array.prototype.with(index, value)
12 |
13 | //* ===============================================
14 | //* Array.findLast() & Array.findLastIndex()
15 | //* ==============================================
16 | //? This function will allow us to find element from the last to first of the array based on a condition.
17 | // const array = [1, 2, 3, 4, 5, 6, 4];
18 | // console.log(array.findLast((elem) => elem > 4));
19 | // console.log(array.findLastIndex((elem) => elem));
20 |
21 | //* ===============================================
22 | //* New Array.prototype functions
23 | //* ==============================================
24 |
25 | const myNames = ["vinod", "bahadur", "thapa", "kodyfier"];
26 |
27 | //? Array.prototype.toReversed();
28 | const reversedNum = myNames.toReversed();
29 | console.log("original", myNames);
30 | console.log("reversed", reversedNum);
31 | //todo if it's not working run in browser
32 |
33 | //? Array.prototype.toSorted(compareFn);
34 | const sortedArr = myNames.toSorted();
35 | console.log("original", myNames);
36 | console.log("sorted", sortedArr);
37 |
38 | //? Array.prototype.toSpliced(start, deleteCount, ...items);
39 | const splicedArr = myNames.toSpliced(1, 1, "thapaTechnical");
40 | console.log("original", myNames);
41 | console.log("spliced", splicedArr);
42 |
43 | //? Array.prototype.with(index, value);
44 | //* The with() method in JavaScript is used to change the value of an element at a specific index in an array. It takes two arguments: the index of the element to be changed and the new value. It returns a new array with the changed element, leaving the original array unchanged.
45 |
46 | const replaceWith = myNames.with(2, "thapaTechnical");
47 | console.log("original", myNames);
48 | console.log("replaced", replaceWith);
49 |
--------------------------------------------------------------------------------
/how_js_works/call_stack.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | Document
9 |
10 |
11 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/how_js_works/closure.js:
--------------------------------------------------------------------------------
1 | //* -------------------------------
2 | //* Closure:
3 | //* -------------------------------
4 |
5 | //? A closure is created when an inner function has access to the variables of its outer function, even after the outer function has finished executing.
6 |
7 | function outerFunction() {
8 | var outerVariable = "I'm from outer";
9 |
10 | function innerFunction() {
11 | console.log(outerVariable);
12 | }
13 | return innerFunction;
14 | }
15 |
16 | var closureFunction = outerFunction();
17 | console.dir(closureFunction);
18 | // closureFunction();
19 |
20 | // Here when we are calling the closureFunction() it is actually going to call the innerFunction() but in our executionContext the outerFunction is already popped out. Still we can access the outerVariable value and how we are able to access it, is what closure all about ?
21 |
22 | // We just need to know that an inner function has always access to the variables of the outer (parent) function. That's it.
23 |
24 | // Why is it like that? It's because the variable object of the parent function stays in memory even after the function returns, and our inner function has access to this variable object through the scope chain.
25 |
26 | // It might be beneficial to clarify that the call stack is simply the execution order and it is not the same thing as the computer's memory, which is where the variables are held. So even though the function was removed from the call stack, its variables are still maintained in memory until they are no longer needed and garbage collection comes and removes them.
27 |
28 | //* also one more example
29 |
30 | function multiplier(factor) {
31 | return function (number) {
32 | console.log(number, factor);
33 | return number * factor;
34 | };
35 | }
36 |
37 | const double = multiplier(2);
38 | console.log(double(5));
39 |
--------------------------------------------------------------------------------
/how_js_works/hoisting.js:
--------------------------------------------------------------------------------
1 | //? Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
2 |
3 | //todo When a function declaration is hoisted, its entire definition (including the body) is moved to the top of its containing scope during the creation phase. This means that you can call the function before it's actually declared in the code, and it will still work as expected.
4 |
5 | let myVar = 10;
6 | const greet = () => {
7 | console.log("Welcome, If you are reading this, Don't forget you are awesome");
8 | };
9 |
10 | console.log(myVar);
11 | greet();
12 |
--------------------------------------------------------------------------------
/how_js_works/index.js:
--------------------------------------------------------------------------------
1 | //* =======================================
2 | //* How JavaScript Works?
3 | //* ===================================
4 |
5 | // https://www.jointjs.com/demos/abstract-syntax-tree
6 |
7 | //! 1: Parsing Phase
8 | //* 1. Lexical analysis
9 | //?Lexical analyzer, also known as a lexer, is the first step in the process of compiling a JavaScript program. It breaks the program down into tokens, which are the basic building blocks of the language.
10 |
11 | //* 2. Syntax analysis
12 | //? Takes the stream of tokens from lexical analysis and checks them for correct syntax. If the syntax is correct, syntax analysis generates a tree-like structure called a parse tree or abstract syntax tree (AST). The AST represents the hierarchical structure of the program.
13 |
14 | //* 2. Compilation (JIT - Just-In-Time Compilation):
15 | //? After the AST is created, the JavaScript engine typically goes through a compilation phase. In modern engines, like V8 in Chrome, SpiderMonkey in Firefox, or JavaScriptCore in Safari, this compilation often involves a combination of two approaches:
16 |
17 | //? Parse and Compile: The engine parses the code and compiles it into an intermediate form, such as bytecode or machine code.
18 |
19 | //? Just-In-Time Compilation (JIT): Some engines use JIT compilation, where the intermediate code is compiled just before execution. This allows the engine to optimize the code based on runtime information, improving performance.
20 |
21 | //* 3. Execution:
22 | //? Once the code is compiled, the JavaScript engine executes it. During execution, the engine creates execution contexts, manages the scope chain, handles variable assignments, and calls functions.
23 |
24 | //? The execution context consists of two phases: the creation phase (where variables and functions are hoisted) and the execution phase (where the code is actually run).
25 |
26 | //? The JavaScript engine uses a call stack to keep track of the execution context. When a function is called, a new frame is added to the stack, and when the function completes, its frame is removed (LIFO - Last In, First Out).
27 |
28 | //* More on inside execution phase
29 | //! Call Stack
30 | //? In order to manage the execution contexts, the JavaScript engine uses a call stack.
31 | //? The call stack is a data structure that keeps track of the currently executing functions in a program. It operates on the Last In, First Out (LIFO) principle, meaning that the last function added to the stack is the first one to be executed and completed.
32 | //! Heap Memory:
33 | //? The heap memory is where dynamically allocated memory resides. This is where objects, closures, and other dynamically allocated data are stored. While the call stack manages the flow of execution and function contexts, the heap memory holds data that is referenced by these execution contexts.
34 |
35 | //! Bonus We will see in PPT with animation
36 | //* Here's a basic overview of how the call stack works:
37 |
38 | //? During the execution of a JavaScript program,
39 |
40 | //? The JavaScript engine goes through the creation phase before executing any code. During this phase, it sets up the global execution context. The global execution context is the first one to be created and pushed onto the call stack. This happens when the JavaScript engine starts executing the code.
41 |
42 | //todo Key activities during the creation phase include:
43 |
44 | //? Creating the global object (window in browsers, global in Node.js).
45 | //? Setting up the this reference.
46 | //? Creating the outer environment reference (which is null for the global context).
47 | //? Creating the variable environment and allocating memory for global variables and functions.
48 |
49 | //* Before executing our code, JavaScript engine scans the code and creates a property for each variable or function in the code. For variable, It reserves space for them in memory and sets an initial value of undefined, and for functions it also reserves space but sets an initial value as a reference to the actual function in memory. That's why we can call a function, but if we try to access a variable, we will get undefined.
50 |
51 | //? Setting up the scope chain, which initially contains only the global scope.
52 |
53 | //! Execution Phase:
54 | //? After the creation phase, the actual code execution takes place. This is when the JavaScript engine goes through the code line by line.
55 | //? Variables are assigned their values, functions are executed, and the program's logic is carried out.
56 |
--------------------------------------------------------------------------------
/how_js_works/scope.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/how_js_works/scope.js:
--------------------------------------------------------------------------------
1 | //* -------------------------
2 | //* Scope in JavaScript
3 | //* -------------------------
4 | //? Scope in JavaScript refers to the context in which variables are declared and accessed. It defines the visibility and lifetime of variables. When a variable is declared, it is bound to a specific scope, and its accessibility is determined by that scope.
5 |
6 | // todo We have a Global Scope, Function Scope and Block Scope
7 |
8 | //* -------------------------
9 | // * Lexical Scoping:
10 | //* -------------------------
11 | // ? Lexical scoping is a way of managing variable access in JavaScript based on the physical structure of the code.
12 |
13 | //? Key Concept: The scope of a variable is determined by its position in the source code, specifically where it is declared.
14 |
15 | //? Lexical scoping in JavaScript is like a set of rules that determines where a variable can be used in your code. It follows the physical structure of your code, so if a variable is declared inside a function or block, it can usually be used only within that function or block.
16 |
17 | // var a = 5;
18 | // var b = 10;
19 | // what will be the value of a?
20 |
21 | //* -------------------------
22 | // * Scope Chaining:
23 | //* -------------------------
24 | //? Definition: Scope chaining is the process by which JavaScript, when looking for the value of a variable, checks the current scope and then looks in the outer (enclosing) scopes until it finds the variable or reaches the global scope.
25 |
26 | //todo Key Concept: Variables in inner scopes have access to variables in their outer scopes, creating a chain of accessible scopes.
27 |
28 | // * Global Scope:
29 | //? Variables: Variables declared outside of any function or block have global scope.
30 | //? Access: Global variables are accessible from any part of the code, including inside functions and blocks.
31 |
32 | // var globalVariable = "I am a global variable";
33 |
34 | // function exampleFunction() {
35 | // console.log(globalVariable); // Accessible within the function
36 | // }
37 |
38 | // console.log(globalVariable); // Accessible globally
39 |
40 | // *Function Scope:
41 | // Variables: Variables declared inside a function have function scope.
42 | // Access: Function-scoped variables are only accessible within the function where they are declared.
43 | // function exampleFunction() {
44 | // var functionScopedVar = "I am a function-scoped variable";
45 | // console.log(functionScopedVar); // Accessible within the function
46 | // }
47 |
48 | // console.log(functionScopedVar); // Error: functionScopedVar is not defined
49 |
50 | // * Block Scope:
51 | // Variables: Variables declared with let and const inside a block (e.g., an if statement or a for loop) have block scope.
52 | // Access: Block-scoped variables are only accessible within the block where they are declared.
53 |
54 | //! ------------------------------
55 | // ! Interview Question
56 | //! -----------------------------
57 |
58 | //! Global Variable vs. Local Variable:
59 | //? Global Variable: A variable declared in the global scope is referred to as a global variable. It has global visibility and can be accessed from anywhere in the code.
60 |
61 | //? Local Variable: A variable declared within a function (function scope) or a block (block scope) is often referred to as a local variable. It has local visibility, limited to the function or block where it's declared.
62 |
63 | const globalVariable = "I'm a global variable";
64 |
65 | function myFunction() {
66 | // Function scope
67 | const functionVariable = "I'm a function variable";
68 |
69 | if (true) {
70 | // Block scope
71 | const blockVariable = "I'm a block variable";
72 | }
73 |
74 | console.log(functionVariable);
75 | }
76 |
77 | myFunction();
78 |
--------------------------------------------------------------------------------
/how_js_works/sync_vs_async.js:
--------------------------------------------------------------------------------
1 | //* Synchronous code executes line by line, blocking further execution until each line is completed, while asynchronous code allows other code to continue executing while it waits for an asynchronous operation to complete.
2 |
3 | // const fun2 = () => {
4 | // console.log("fun2 starts and ends");
5 | // };
6 |
7 | // const fun1 = () => {
8 | // console.log("fun1 is start");
9 | // fun2();
10 | // console.log("fun1 ends");
11 | // };
12 |
13 | // fun1();
14 |
15 | const fun2 = () => {
16 | setTimeout(() => {
17 | console.log("fun2 starts and ends");
18 | }, 2000);
19 | };
20 |
21 | const fun1 = () => {
22 | console.log("fun1 is start");
23 | fun2();
24 | console.log("fun1 ends");
25 | };
26 | fun1();
27 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
12 |
13 |
14 |
Welcome to world best Javascript Course
15 |
16 |
17 |
18 |
19 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/intro.js:
--------------------------------------------------------------------------------
1 | console.log("I am an external JS File");
2 |
--------------------------------------------------------------------------------
/objects/bonus.js:
--------------------------------------------------------------------------------
1 | //* call, apply, and bind are methods available in JavaScript for managing the this value of a function.
2 | //! all 3 methods are only used in function not in object
3 |
4 | //* call:
5 | //! Syntax: function.call(thisArg, arg1, arg2, ...)
6 | //? Invokes a function with a specified this value and individual arguments.
7 |
8 | // function greet(message) {
9 | // console.log(`${message}, ${this.name}!`);
10 | // }
11 |
12 | // const person = {
13 | // name: "John",
14 | // };
15 |
16 | // greet.call(person, "hello");
17 |
18 | //* apply:
19 | // Syntax: function.apply(thisArg, [arg1, arg2])
20 | //? Invokes a function with a specified this value and an array or array-like object of arguments.
21 |
22 | // function greet(message) {
23 | // console.log(`${message}, ${this.name}!`);
24 | // }
25 |
26 | // const person = { name: "John" };
27 |
28 | // greet.apply(person, ["hello"]);
29 |
30 | //todo In modern JavaScript, with the introduction of the spread operator (...), the need for apply has diminished, and you can often achieve the same result with call and the spread operator.
31 |
32 | // function greet(message, punctuation) {
33 | // console.log(`${message}, ${this.name}${punctuation}`);
34 | // }
35 |
36 | // const person = { name: "John" };
37 | // const argsArray = ["Hello", "!"];
38 |
39 | // // Using apply
40 | // greet.apply(person, argsArray);
41 | // // Output: Hello, John!
42 |
43 | // // Using call and spread operator
44 | // greet.call(person, ...argsArray);
45 | // // Output: Hello, John!
46 |
47 | //* bind:
48 | //? Syntax: function.bind(thisArg, arg1, arg2, ...)
49 | //* Creates a new function with a specified this value and any initial arguments. Unlike call and apply, bind does not immediately invoke the function but returns a new function that can be invoked later.
50 |
51 | //? Use Cases:
52 | //* Use call when you want to invoke a function with a specific this value and individual arguments.
53 |
54 | //* Use apply when you want to invoke a function with a specific this value and an array or array-like object of arguments.
55 |
56 | //* Use bind when you want to create a new function with a specific this value and initial arguments without immediately invoking it. The new function can be invoked later.
57 |
58 | const bioData = {
59 | name: "Thapa Technical",
60 | age: 30,
61 | gender: "Male",
62 |
63 | greet: function () {
64 | console.log(
65 | `Hi, I'm ${this.name}. I'm ${this.age} years old, and I identify as ${this.gender}.`
66 | );
67 | },
68 | };
69 | // // Example usage:
70 | // // bioData.greet();
71 | // bioData.greet.call(bioData);
72 |
73 | //? Imagine you have two objects: bioData and student. The greet method is defined in the bioData object, and you want to use it to display the information from the student object.
74 |
75 | let student = { name: "vinod", age: "29", gender: "male" };
76 | // bioData.greet.call(student);
77 |
78 | // bioData.greet.apply(student);
79 |
80 | // student = bioData.greet.bind(student);
81 | // student();
82 |
83 | // Explanation
84 | // The greet method is defined in the bioData object, and it uses this to refer to its own properties.
85 | // student is a separate object with properties like name, age, and gender.
86 | // By using call(student), you are telling the greet method to temporarily consider the student object as its own object (this), allowing it to access and display the properties of the student object.
87 | // So, call is a way to borrow a method from one object and use it for another object, temporarily setting the this value to the provided object.
88 |
89 | //* the main difference is that call immediately invokes the function with the specified this value, while bind creates a new function with the specified this value and initial arguments but doesn't invoke the function immediately. You need to invoke the new function returned by bind separately.
90 |
91 | // // more example
92 | function greet(message) {
93 | console.log(`${message}, ${this.name}!`);
94 | }
95 |
96 | const person = { name: "vinod" };
97 |
98 | greet.call(person, "Hello");
99 | greet.apply(person, ["Hey"]);
100 |
101 | const anotherWay = greet.bind(person, "hello");
102 | anotherWay();
103 |
--------------------------------------------------------------------------------
/objects/index.js:
--------------------------------------------------------------------------------
1 | //* ==============================
2 | //* Object in JavaScript
3 | //* ==============================
4 | //? Objects are a fundamental part of JavaScript, providing a way to group related data and functions together. In JavaScript, an object is a collection of key-value pairs, where each key is a string (or a symbol) and each value can be any data type, including other objects. Objects can have properties and methods, making them versatile for various use cases.
5 |
6 | //* ==============================
7 | //* Creating Objects:
8 | //* ==============================
9 | //? There are several ways to create objects in JavaScript. The most common one is using object literals:
10 |
11 | // const product = {
12 | // id: 1,
13 | // pName: "laptop",
14 | // };
15 | // let person = {
16 | // name: "Vinod",
17 | // age: 30,
18 | // isStudent: false,
19 | // greet: function () {
20 | // console.log("Welcome to World Best CSS Course");
21 | // },
22 | // };
23 |
24 | let person = {
25 | name: "Vinod",
26 | age: 30,
27 | "is'Student": false,
28 | greet: function () {
29 | console.log("Welcome to World Best JavaScript Course");
30 | },
31 | };
32 |
33 | //* ==============================
34 | //* Accessing Properties:
35 | //* ==============================
36 | //? You can access object properties using dot notation or square bracket notation:
37 |
38 | // console.log(person.age);
39 | // console.log(person.name);
40 | // console.log(person[`is'Student`]);
41 |
42 | //* =================================
43 | //* Adding and Modifying Properties:
44 | //* =================================
45 | //? You can add new properties or modify existing ones:
46 | // person["job"] = "web dev";
47 | // // person.age = 18;
48 | // person["age"] = 20;
49 |
50 | // console.log(person);
51 |
52 | //* =================================
53 | //* Methods:
54 | //* =================================
55 | //? Methods in objects are functions associated with the object. They can be invoked using the same notation as properties:
56 |
57 | // person.greet();
58 |
59 | //* ========================================
60 | //* We can add dynamic keys in an object
61 | //* ========================================
62 |
63 | // let idType = "studentId";
64 |
65 | // let student = {
66 | // [idType]: "A123456", // Dynamic key based on idType
67 | // sName: "Vinod",
68 | // sAge: 29,
69 | // isStudent: true,
70 | // greet: function () {
71 | // console.log(
72 | // `Hey, my ${idType} is ${student[idType]} and my name is ${student.sName}.`
73 | // );
74 | // },
75 | // };
76 |
77 | // student.greet();
78 |
79 | //? useCase: when we want to get the user name and value in react
80 |
81 | //* =================================
82 | //* Data Modeling:
83 | //* =================================
84 | //? Data modeling is the process of creating a visual representation of either a whole information system or parts of it to communicate connections between data points and structures. The goal is to illustrate the types of data used and stored within the system, the relationships among these data types, the ways the data can be grouped and organized and its formats and attributes.
85 |
86 | // Objects are excellent for modeling real-world entities. For instance, you might represent a car, a user, or a product as an object with properties like color, brand, username, etc.
87 |
88 | // let car = {
89 | // brand: "Toyota",
90 | // model: "Camry",
91 | // year: 2022,
92 | // start: function () {
93 | // console.log("Engine started!");
94 | // },
95 | // };
96 |
97 | //* =====================================
98 | //* Interview Question
99 | //* ======================================
100 |
101 | //! Explain the difference between passing objects by reference and by value in JavaScript. Provide an example to demonstrate each scenario.
102 |
103 | //? sol: In JavaScript, primitive data types like numbers and strings are passed by value, while objects are passed by reference.
104 | //? Passing by value: When passing by value, a copy of the primitive value is created and passed to the function or assigned to a variable. Any changes made to the copy do not affect the original value.
105 |
106 | // let a = 10;
107 | // const modifyValue = (x) => (x = 20);
108 |
109 | // console.log(modifyValue(a));
110 | // console.log(a);
111 |
112 | //? Passing by reference: When passing by reference, a reference to the memory location of the object is passed to the function or assigned to a variable. Any changes made to the object through this reference will affect the original object.
113 |
114 | // let obj = { id: 5, name: "kodyfier" };
115 |
116 | // let obj1 = obj;
117 |
118 | // obj1.name = "thapa technical";
119 | // console.log(obj1);
120 | // console.log("original", obj);
121 |
122 | // To avoid this behavior and create a true copy of the object, you can use methods like Object.assign() or the spread operator (...):
123 |
124 | //? Object.assign() is used to copy properties from one or more source objects to a target object.
125 |
126 | // let obj = { id: 5, name: "kodyfier" };
127 | // let obj1 = {};
128 | // let newObj = Object.assign(obj1, obj);
129 |
130 | // newObj.name = "thapa technical";
131 | // console.log(newObj);
132 | // console.log("original", obj);
133 |
134 | //* =====================================
135 | //* Comparison by Reference:
136 | //* ======================================
137 |
138 | //? Two objects are equal only if they refer to the same object.
139 | //? Independent objects (even if they look alike) are not equal:
140 |
141 | // const obj1 = { name: "vinod" };
142 | // const obj2 = { name: "vinod" };
143 | // const obj3 = obj1;
144 |
145 | // // const isEqual = obj1 == obj2 ? true : false;
146 | // const isEqual = obj1 == obj3 ? true : false;
147 | // console.log(isEqual);
148 |
149 | //* =====================================
150 | //* JSON (JavaScript Object Notation):
151 | //* ======================================
152 |
153 | //?JSON is a data interchange format derived from JavaScript objects. Objects can be easily converted to JSON and vice versa.
154 |
155 | // let student = {
156 | // id: 1,
157 | // sName: "Vinod",
158 | // sAge: 29,
159 | // isStudent: false,
160 | // greet: function () {
161 | // console.log(
162 | // `hey my id is ${student.identity} & my name is ${student.sName}`
163 | // );
164 | // },
165 | // };
166 |
167 | // let jsonData = JSON.stringify(student);
168 | // console.log(jsonData);
169 | // let parsedObject = JSON.parse(jsonData);
170 | // console.log(parsedObject);
171 |
172 | //* =====================================
173 | //* "this" Object
174 | //* ======================================
175 |
176 | //? In JavaScript, the this keyword refers to an object.
177 |
178 | // Which object depends on how this is being invoked (used or called).
179 |
180 | // The this keyword refers to different objects depending on how it is used:
181 |
182 | // In an object method, this refers to the object.
183 | // Alone, this refers to the global object.
184 | // In a function, this refers to the global object.
185 | // In a function, in strict mode, this is undefined.
186 | // In an event, this refers to the element that received the event.
187 | // Methods like call(), apply(), and bind() can refer this to any object.
188 |
189 | // Note
190 | // this is not a variable. It is a keyword. You cannot change the value of this.
191 | // ("use strict");
192 |
193 | // x = 5;
194 | // console.log(x);
195 |
196 | // function callme() {
197 | // console.log(this);
198 | // }
199 |
200 | // callme(); // try to run on browser console
201 |
202 | //todo Let's check the this keyword values in an object methods
203 |
204 | //* Regular Function Expression:
205 | // const obj = {
206 | // name: "Kodyfier",
207 | // greet: function () {
208 | // console.log(this);
209 | // },
210 | // };
211 |
212 | // obj.greet();
213 |
214 | //* In this example, the greet method is defined using the "Method Shorthand" syntax. It's a more concise way to define methods in object literals.
215 | // const obj = {
216 | // name: "Kodyfier",
217 | // greet() {
218 | // console.log(this);
219 | // },
220 | // };
221 |
222 | // obj.greet();
223 |
224 | //* Fat Arrow Function
225 | // const obj = {
226 | // name: "thapa technical",
227 | // greet: () => {
228 | // console.log(this);
229 | // },
230 | // };
231 |
232 | // obj.greet();
233 |
234 | //* =====================================
235 | //* Objects Useful Methods
236 | //* ======================================
237 |
238 | // const product = {
239 | // id: 1,
240 | // name: "Laptop",
241 | // category: "Computers",
242 | // brand: "ExampleBrand",
243 | // price: 999.99,
244 | // stock: 50,
245 | // description:
246 | // "Powerful laptop with a quad-core i5 processor, 8GB RAM, 256GB SSD, and a 14-inch FHD display.",
247 | // image: "image link will be added during projects",
248 | // };
249 |
250 | //? 1: Object.keys(): Returns an array containing the names of all enumerable own properties of an object.
251 |
252 | // let keys = Object.keys(product);
253 | // console.log(keys);
254 |
255 | //? 2: Object.values(): Returns an array containing the values of all enumerable own properties of an object.
256 | // let values = Object.values(product);
257 | // console.log(values);
258 |
259 | //? 3: Object.entries(): Returns an array containing arrays of key-value pairs for each enumerable own property of an object.
260 | // let entries = Object.entries(product);
261 | // console.log(entries);
262 |
263 | //? 4: Object.hasOwnProperty(): Returns a boolean indicating whether the object has the specified property as an own property.
264 | // console.log(product.hasOwnProperty("name")); // Output: true
265 | // console.log(product.hasOwnProperty("isStudent")); // Output: false
266 |
267 | //? 5: Object.assign(): Copies the values of all enumerable own properties from one or more source objects to a target object.
268 | // const target = { a: 1, b: 5 };
269 | // const source = { b: 3, c: 4 };
270 | // const mergedObject = Object.assign(target, source);
271 | // console.log(mergedObject); // Output: { a: 1, b: 3, c: 4 }
272 |
273 | //? 6: Object.freeze(): Freezes an object, preventing new properties from being added to it and existing properties from being modified or deleted.
274 | // Object.freeze(product);
275 | // product.id = "5656";
276 | // console.log(product);
277 |
278 | //* =====================================
279 | //* Interview Question - Objects
280 | //* ======================================
281 |
282 | //! 1: What will be the output?
283 |
284 | // const target = { a: 1, b: 2 };
285 | // const source = { b: 3, c: 4 };
286 |
287 | // const mergedObject = Object.assign({}, target, source);
288 | // console.log(mergedObject);
289 |
290 | //* ===============================================
291 | //* Interview Question - Object Manipulation:
292 | //* ================================================
293 | //! Problem: Given an object representing a student, write a function to add a new subject with its corresponding grade to the student's record. Also check if the grades property is present or not?
294 |
295 | // let student = {
296 | // name: "Bob",
297 | // age: 20,
298 | // grades: {
299 | // math: 90,
300 | // science: 85,
301 | // history: 88,
302 | // },
303 | // };
304 |
305 | // const addSubjectGrade = (student, subject, marks) => {
306 | // if (!student.grades) {
307 | // student.grades = {};
308 | // }
309 |
310 | // return (student.grades[subject] = marks);
311 | // };
312 |
313 | // addSubjectGrade(student, "computer", 92);
314 | // console.log(student);
315 |
316 | //* ===============================================
317 | //* Interview Question - Object Comparison:
318 | //* ================================================
319 | //! Problem: Write a function that compares two objects to determine if they have the same properties and values.
320 |
321 | // const areObjectsEqual = (obj1, obj2) => {
322 | // // if (obj1.length != obj2.length) {
323 | // // console.log("hi");
324 | // // return false;
325 | // // }
326 | // let o1 = Object.keys(obj1);
327 | // let o2 = Object.keys(obj2);
328 |
329 | // if (o1.length != o2.length) {
330 | // console.log("There keys are not same");
331 | // return false;
332 | // }
333 |
334 | // for (let key in obj1) {
335 | // if (obj1[key] !== obj2[key]) {
336 | // return false;
337 | // }
338 | // }
339 |
340 | // return true;
341 | // };
342 |
343 | // // Example usage:
344 | // let objA = { name: "Alice", age: 26, city: "New York" };
345 | // let objB = { name: "Alice", age: 26, city: "New York" };
346 | // let objC = { name: "Bob", age: 30, city: "San Francisco" };
347 |
348 | // console.log(areObjectsEqual(objA, objB)); // Should return true
349 | // console.log(areObjectsEqual(objA, objC)); // Should return false
350 |
351 | //* ===============================================
352 | //* Interview Question - Object Transformation:
353 | //* ================================================
354 | //! Problem: Write a function that transforms an array of an objects into an object where the keys are the objects' ids.
355 |
356 | let inputArray = [
357 | { id: 1, name: "Alice" },
358 | { id: 2, name: "Bob" },
359 | { id: 3, name: "Charlie" },
360 | ];
361 |
362 | const arrayToObj = (arr) => {
363 | // console.log(arr[2].id);
364 | let obj = {};
365 | for (let key of arr) {
366 | console.log(key.id, key);
367 | obj[key.id] = key;
368 | // console.log(key);
369 | }
370 | return obj;
371 | };
372 |
373 | console.log(arrayToObj(inputArray));
374 | // Should print: { '1': { id: 1, name: 'Alice' }, '2': { id: 2, name: 'Bob' }, '3': { id: 3, name: 'Charlie' } }
375 |
--------------------------------------------------------------------------------
/timeBasedEvents/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
13 | Document
14 |
15 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
113 |
114 |
115 |
--------------------------------------------------------------------------------
/timeBasedEvents/index.js:
--------------------------------------------------------------------------------
1 | //* =========================================
2 | //* Timing Based Events in JavaScript
3 | //* =========================================
4 |
5 | //* 1. setTimeout:
6 | //? The setTimeout function is used to execute a function or code block after a specified delay in milliseconds.
7 |
8 | // function delayedFunction(x) {
9 | // console.log("This function was delayed by 2000 milliseconds (2 seconds).", x);
10 | // }
11 |
12 | // setTimeout(delayedFunction, 2000);
13 | // setTimeout(() => delayedFunction(5), 2000);
14 |
15 | //* 2. setInterval:
16 | //? The setInterval function is used to repeatedly execute a function or code block at a specified interval in milliseconds.
17 |
18 | //? ex- mind game of counting seconds on mind and after every 5secs we need to draw a straight line on paper.
19 | // and it will continue till I told you to stop
20 |
21 | // function repeatedFunction() {
22 | // console.log(
23 | // "This function will be repeated every 1000 milliseconds (1 second)."
24 | // );
25 | // }
26 |
27 | // setInterval(repeatedFunction, 1000);
28 |
29 | //* 3. Clearing Timeout with clearTimeout:
30 | //? If you want to cancel a scheduled timeout before it occurs, you can use the clearTimeout function.
31 |
32 | //? The global clearTimeout() method cancels a timeout previously established by calling setTimeout().
33 |
34 | // Syntax:
35 | //* clearTimeout(timeoutID);
36 |
37 | // function delayedFunction() {
38 | // console.log("This function was delayed by 2000 milliseconds (2 seconds).");
39 | // }
40 | // const myWork = setTimeout(delayedFunction, 2000);
41 | // clearTimeout(myWork);
42 |
43 | //todo Cancel the timeout before it occurs
44 |
45 | //* 4. Clearing Interval with clearInterval:
46 | //? If you want to cancel a scheduled interval before it occurs, you can use the clearInterval function.
47 |
48 | //? The global clearInterval() method cancels a timeout previously established by calling setInterval().
49 |
50 | // Syntax:
51 | // clearInterval(intervalID);
52 |
53 | // function repeatedFunction() {
54 | // console.log("This function repeats every 1000 milliseconds (1 second).");
55 | // }
56 |
57 | // const intervalID = setInterval(repeatedFunction, 1000);
58 |
59 | // clearInterval(intervalID);
60 |
61 | //todo Cancel the interval
62 |
63 | //* =========================================
64 | //* Challenge Time
65 | //* =========================================
66 |
67 | //! Write a JavaScript program that defines a function called repeatedFunction. This function should log the message "This function repeats every 1000 milliseconds (1 second)" to the console. Then, set up an interval using setInterval() to call repeatedFunction every 1000 milliseconds. Additionally, after 5 seconds have elapsed, use setTimeout() to clear the interval previously set up. Make sure to log the message "Interval cleared after 5 seconds." when the interval is cleared.
68 |
69 | // const repeatedFunction = () => {
70 | // console.log("This function repeats every 1000 milliseconds (1 second)");
71 | // };
72 |
73 | // repeatedFunction();
74 |
75 | // const intervalID = setInterval(repeatedFunction, 1000);
76 |
77 | // setTimeout(() => {
78 | // clearInterval(intervalID);
79 | // }, 5000);
80 |
--------------------------------------------------------------------------------
/timeBasedEvents/project.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 |
11 |
49 |
50 |
51 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/windows/bom/index.js:
--------------------------------------------------------------------------------
1 | //* =========================================
2 | //* BOM Properties:
3 | //* =========================================
4 |
5 | // ?window properties
6 |
7 | //? window.console:
8 | // Represents the browser's debugging console.
9 | // Allows logging messages using methods like log(), warn(), and error().
10 |
11 | //? window.innerWidth / window.innerHeight:
12 | // Provides the width and height of the browser's content area (excluding toolbars and scrollbars).
13 |
14 | //? window.scrollX / window.scrollY:
15 | // Represents the number of pixels that the document is currently scrolled horizontally and vertically.
16 |
17 | //? window.outerWidth / window.outerHeight:
18 | // Provides the width and height of the whole browser window (including toolbars and borders).
19 |
20 | //? window.localStorage:
21 | // Provides a way to store key-value pairs persistently on the user's device.
22 | // Allows storing data beyond the lifetime of a single page session.
23 |
24 | //* Functions alert/confirm/prompt are also a part of BOM:
25 | // They are directly not related to the document, but represent pure browser methods of communicating with the user.
26 |
27 | //? window Object:
28 | //? Represents the global window containing the BOM.
29 | // Example: window.location, window.innerWidth, window.innerHeight.
30 |
31 | //? navigator Object:
32 | // Provides information about the browser.
33 | // Example: navigator.userAgent, navigator.language.
34 |
35 | //? location Object:
36 | // Represents the current URL of the browser.
37 | // Example: window.location.href, window.location.hostname.
38 |
39 | //? history Object:
40 | // Represents the session history, allowing navigation through the browser history.
41 | // Example: window.history.back(), window.history.forward().
42 |
43 | //? screen Object:
44 | // Represents information about the user's screen.
45 | // Example: window.screen.width, window.screen.height
46 |
47 | //? window.localStorage, window.sessionStorage
48 | // Objects for storing data persistently or for the duration of a page session.
49 |
50 | //? document Object:
51 | // Represents the DOM of the currently displayed document.
52 |
53 | //* navigator Object:
54 | //? The JavaScript navigator object is used for browser detection. It can be used to get browser information such as appName, appCodeName, userAgent etc.
55 |
56 | //? navigator.userAgent (Property):
57 | // Returns the user agent string of the browser.
58 | // Example: console.log(navigator.userAgent).
59 |
60 | //? navigator.language (Property):
61 | // Returns the language preference of the user's browser.
62 | // Example: console.log(navigator.language).
63 |
64 | //? navigator.cookieEnabled (Property):
65 | // Indicates whether cookies are enabled in the browser.
66 | // Example: console.log(navigator.cookieEnabled).
67 |
68 | //? navigator.platform (Property):
69 | // Returns the platform on which the browser is running.
70 | // Example: console.log(navigator.platform).
71 |
72 | //? navigator.onLine (Property):
73 | // Indicates whether the browser is online.
74 | // Example: console.log(navigator.onLine).
75 |
76 | //* 2: History object
77 |
78 | // The JavaScript history object represents an array of URLs visited by the user. By using this object, you can load previous, forward or any particular page.
79 |
80 | //* 3: location Object:
81 |
82 | //? window.location.href (Property):
83 | // Returns or sets the complete URL of the current page.
84 | // Example: console.log(window.location.href).
85 |
86 | //? window.location.hostname (Property):
87 | // Returns the domain name of the web host.
88 | // Example: console.log(window.location.hostname).
89 |
90 | //? window.location.assign(url) (Method):
91 | // Navigates to the specified URL.
92 | // Example: window.location.assign("https://www.example.com").
93 |
94 | //? window.location.reload(forceReload) (Method):
95 | // Reloads the current page.
96 | // Example: window.location.reload(true).
97 |
98 | //? window.location.search (Property):
99 | // Returns the query string part of the URL.
100 | // Example: console.log(window.location.search)
101 | // o/p = "?name=John&age=25"
102 |
103 | //* 4: screen Object:
104 | //? window.screen.width and window.screen.height (Properties):
105 | // Represent the width and height of the user's screen.
106 | // Example: console.log(window.screen.width).
107 |
108 | //? window.screen.availWidth and window.screen.availHeight (Properties):
109 | // Represent the available width and height of the user's screen (excluding taskbars).
110 | // Example: console.log(window.screen.availWidth).
111 |
112 | //? window.screen.colorDepth (Property):
113 | // Returns the number of bits used to represent the color of each pixel.
114 | // Example: console.log(window.screen.colorDepth).
115 |
116 | //? window.screen.orientation (Property):
117 | // Returns the current orientation of the user's screen.
118 | // Example: console.log(window.screen.orientation).
119 |
120 | //? window.screen.pixelDepth (Property):
121 | // Returns the number of bits used to represent each pixel.
122 | // Example: console.log(window.screen.pixelDepth).
123 |
--------------------------------------------------------------------------------
/windows/dom/domCrud.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Document
6 |
10 |
11 |
19 |
20 |
21 |
22 |
28 |
29 |
30 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/windows/dom/index.js:
--------------------------------------------------------------------------------
1 | //* ==============================
2 | //* DOM IN JAVASCRIPT
3 | //* ==============================
4 |
5 | //? When a web browser loads an HTML document, it parses the HTML source code and creates a tree-like structure known as the Document Object Model (DOM). This DOM tree represents the structure of the HTML document, with each HTML element being a node in the tree.
6 |
7 | //? This entire DOM tree is then accessible to JavaScript as an object. JavaScript can interact with this object to manipulate the content, structure, and style of the document dynamically. The DOM essentially serves as an interface between the HTML document and JavaScript, providing a way for scripts to access and modify the document's structure and content.
8 |
9 | //todo The Document Object Model (DOM) is an Application Programming Interface (API). The DOM Tree is the structure of your HTML document, as represented by the DOM API. As stated, this API then gives us many methods and properties that we can use to manipulate the Tree, and therefore, by extension, the document.
10 |
11 | //* Here is a types of nodes in js:
12 |
13 | //? Element node: An HTML tag, the tree building blocks.
14 |
15 | //? Text node: In the DOM tree, text content, including new lines, spaces, and tabs, is treated as text nodes.
16 |
17 | //? Attribute node: An attribute of an element.
18 |
19 | //? Comment node: Represent comments within the HTML document.
20 |
21 | //? Processing instruction node: A processing instruction node, such as xml-stylesheet … ?>.
22 |
23 | //? Document node: A document node.
24 |
25 | //? Document type node: A document type node, such as .
26 |
27 | //* ==============================
28 | //* DOM Properties and Methods
29 | //* ==============================
30 | //! DOM Properties:
31 | // document
32 | // getElementById(id)
33 | // getElementsByClassName(className)
34 | // getElementsByTagName(tagName)
35 | // querySelector(selector)
36 | // querySelectorAll(selector)
37 | // innerHTML
38 | // textContent
39 | // style
40 |
41 | //! DOM Methods:
42 | // createElement(tagName)
43 | // appendChild(node)
44 | // removeChild(node)
45 | // addEventListener(event, function)
46 | // removeEventListener(event, function)
47 | // setAttribute(name, value)
48 | // getAttribute(name)
49 | // parentNode / parentElement
50 | // childNodes / children
51 | // firstChild / firstElementChild
52 | // lastChild / lastElementChild
53 | // nextSibling / nextElementSibling
54 | // previousSibling / previousElementSibling
55 | // closest(selector)
56 | // forEach (Array.from)
57 |
58 | //* ==============================
59 | //* DOM Navigation
60 | //* ==============================
61 |
62 | //? document represents the entire document
63 | // console.log(document);
64 |
65 | //? Document.documentElement returns the Element that is the root element of the document (for example, the element for HTML documents).
66 |
67 | //? parentNode / parentElement:
68 | // Navigate to the parent node or element.
69 |
70 | // Document and DocumentFragment nodes can never have a parent, so parentNode will always return null. It also returns null if the node has just been created and is not yet attached to the tree.
71 |
72 | //? childNodes / children:
73 | // Navigate to child nodes or elements.
74 |
75 | // childNodes is a property that returns a NodeList containing all child nodes of a given element, including text nodes and comment nodes.
76 |
77 | //? firstChild / firstElementChild:
78 | // Navigate to the first child node or element.
79 |
80 | //todo The Element suffix in firstElementChild and similar properties signifies that only element nodes are considered.
81 |
82 | //? lastChild / lastElementChild:
83 | // Navigate to the last child node or element.
84 |
85 | //? nextSibling / nextElementSibling:
86 | // Navigate to the next sibling node or element.
87 |
88 | //? previousSibling / previousElementSibling:
89 | // Navigate to the previous sibling node or element.
90 |
91 | //? closest(selector):
92 | // Find the closest ancestor of the current element that matches a given selector.
93 |
94 | //* ==============================
95 | //* DOM Filtering
96 | //* ==============================
97 |
98 | //? childNodes / children:
99 | // Get a NodeList or HTMLCollection and filter based on your criteria.
100 |
101 | //? Filtering Siblings:
102 | //? nextSibling / nextElementSibling
103 | //? previousSibling / previousElementSibling
104 |
105 | //? closest(selector):
106 | //? Find the closest ancestor that matches a given selector.
107 | //? The closest(selector) method is used to find the closest ancestor of an element that matches a specified CSS selector. This method traverses up the DOM tree, starting from the current element, and returns the first ancestor that matches the provided selector. If no matching ancestor is found, it returns null.
108 |
109 | //* ==============================
110 | //* DOM Searching
111 | //* ==============================
112 | //? getElementById(id): Find an element by its ID.
113 |
114 | //? getElementsByClassName(className): Find elements with a specific class name.
115 |
116 | //? getElementsByTagName(tagName): Find elements with a specific tag name.
117 |
118 | //? querySelector(selector): Find the first element that matches the specified CSS selector.
119 |
120 | //? querySelectorAll(selector): Find all elements that match the specified CSS selector.
121 |
122 | //* ============================================
123 | //* DOM - CRUD (Create, Read, Update, Delete):
124 | //* ============================================
125 |
126 | //? createElement(tagName): Create a new HTML element.
127 |
128 | //? appendChild(node): Append a node as the last child of a parent node.
129 |
130 | //? removeChild(node): Remove a child node from its parent.
131 |
132 | //? addEventListener(event, function): Create an event listener to handle events.
133 |
134 | //? removeEventListener(event, function): Remove an event listener.
135 |
136 | //? setAttribute(name, value): Set the value of an attribute on an element.
137 |
138 | //? getAttribute(name): Get the value of a specific attribute on an element.
139 |
140 | //? innerHTML: Read or update the HTML content of an element.
141 |
142 | //? textContent: Read or update the text content of an element.
143 |
144 | //* =============================
145 | //* DOM - Iteration
146 | //* =============================
147 |
148 | //? Iteration:
149 | //? forEach (Array.from): Iterate through NodeList or convert to an array for more flexible manipulation.
150 |
151 | // Very important
152 | //* When you use the browser's developer tools console to select an element and change its text content using JavaScript, you are directly manipulating the DOM object in memory. Since the DOM is a live representation of the document, any changes you make to the DOM objects are immediately reflected in the rendered web page.
153 |
154 | //* However, these changes are typically temporary and exist only in the current session. When you refresh the page or navigate away, the browser reloads the original HTML document from the server, and the DOM is reconstructed during the parsing process. Any modifications made to the DOM objects during the previous session are lost, and the page reverts to its original state.
155 |
--------------------------------------------------------------------------------
/windows/style.css:
--------------------------------------------------------------------------------
1 | * {
2 | margin: 0;
3 | padding: 0;
4 | box-sizing: border-box;
5 | }
6 | html {
7 | color: #fff;
8 | font-size: 62.5%;
9 | }
10 | body {
11 | font-family: "Urbanist", sans-serif;
12 | background-color: #1b1b1d;
13 | }
14 |
15 | h1 {
16 | font-size: 3.6rem;
17 | margin-top: 4.8rem;
18 | }
19 | hr {
20 | margin-bottom: 3.2rem;
21 | }
22 | p,
23 | li,
24 | button {
25 | font-size: 1.7rem;
26 | letter-spacing: 0.1rem;
27 | font-family: "Urbanist", sans-serif;
28 | line-height: 1.6;
29 | }
30 | button {
31 | background-color: #f5ee62;
32 | padding: 0.6rem 2.4rem;
33 | border-radius: 10rem;
34 | margin-right: 3.6rem;
35 | cursor: pointer;
36 | transition: all 0.3s linear;
37 |
38 | &:hover {
39 | box-shadow: inset 0 0 0 0.2rem #f5ee62;
40 | background-color: transparent;
41 | color: #f5ee62;
42 | }
43 | }
44 |
45 | .para:hover {
46 | color: red;
47 | cursor: pointer;
48 | }
49 |
--------------------------------------------------------------------------------