-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloops.js
245 lines (207 loc) · 7.24 KB
/
loops.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Loops in Javascript
// Loops are used to execute a piece of code again & agin
// ============================================
// JavaScript Looping Constructs: Detailed Explanations and Advanced Examples
// ============================================
// -----------------------------
// Basic For Loop
// -----------------------------
// A for loop is structured with three parts:
// 1. Initialization: executed once at the start (e.g., let i = 1)
// 2. Condition: checked before each iteration; the loop runs if true
// 3. Update: executed after each iteration (e.g., i++)
//
// General Syntax:
// for (initialization; condition; update) {
// // Code block to execute each iteration
// }
// Example 1: Print a message 5 times.
// for (let i = 1; i <= 5; i++) {
// // Output the iteration number and a message.
// console.log(`Iteration ${i}: Aditya Gupta`);
// }
// Example 2: Sum of numbers from 1 to 5.
// let sum = 0;
// for (let i = 1; i <= 5; i++) {
// // Add current i to the sum.
// sum += i; // Progression: 1, 3, 6, 10, 15
// }
// console.log(`Sum of numbers 1 to 5 is: ${sum}`);
// // Example 3: Sum numbers from 1 to a dynamic limit (n).
// let sumOfNumbers = 0;
// const n = 10; // Change n to sum a different range.
// for (let j = 1; j <= n; j++) {
// sumOfNumbers += j;
// }
// console.log(`Sum of numbers from 1 to ${n} is: ${sumOfNumbers}`);
// Example 4: Show incremental accumulation with logging.
// let total = 0;
// const m = 20;
// for (let k = 1; k <= m; k++) {
// total += k;
// console.log(`k = ${k}`);
// console.log(`Total value after adding ${k} is: ${total}`);
// }
// Note: Infinite Loop Example (Do NOT run this!)
// The condition never becomes false, which creates an endless loop.
/*
for (let i = 1; i >= 0; i++) {
console.log("i =", i);
}
*/
// -----------------------------
// While Loop
// -----------------------------
// Executes a block of code as long as the condition is true.
// The condition is evaluated before the code block runs,
// meaning it might not run at all if the condition is false initially.
// let i = 1;
// while (i <= 5) {
// console.log(`While Loop iteration ${i}: Aditya Gupta`);
// i++; // Increment to eventually falsify the condition.
// }
// -----------------------------
// Do-While Loop
// -----------------------------
// Similar to the while loop but guarantees that the code block
// executes at least once because the condition is evaluated after the code runs.
// let j = 1;
// do {
// console.log(`Do-While Loop iteration ${j}`);
// j++;
// } while (j <= 5);
// -----------------------------
// Advanced Loop Examples
// -----------------------------
// 1. For-Of Loop:
// Ideal for iterating or declaring continuosly over iterable objects like arrays or strings.
// It gives direct access to the value of each element.
// const fruits = ["Apple", "Banana", "Cherry"];
// for (const fruit of fruits) {
// console.log(`Fruit: ${fruit}`);
// }
// Used for strings & arrays
// Example to find the each variable's char or letter count :
// let string = "all is well";
// for(let i of string){
// console.log("i is = ", i);
// }
// Example for finding the length or size of string
// let str = "Javascript";
// let size = 0;
// for (let i of str){
// console.log("i = " + i);
// size++;
// }
// console.log("String size = ", size);
// // Output will be : i = J
// loops.js:110 i = a
// loops.js:110 i = v
// loops.js:110 i = a
// loops.js:110 i = s
// loops.js:110 i = c
// loops.js:110 i = r
// loops.js:110 i = i
// loops.js:110 i = p
// loops.js:110 i = t
// loops.js:114 String size = 10
// // 2. For-In Loop:
// Used for Objects & arrays
// Used for iterating over the enumerable properties of an object.
// Useful when you need both the key and value.
// const person = {
// name: "Aditya",
// age: 30,
// occupation: "Developer"
// };
// for (const key in person) {
// // hasOwnProperty check ensures the property belongs to the object itself.
// if (person.hasOwnProperty(key)) {
// console.log(`${key}: ${person[key]}`);
// }
// }
// Example : for finding key
// let classroom = {
// whiteboard : 5,
// chock : 10,
// duster : 12,
// studentcapacity : 50,
// group : "PCM science group",
// };
// for(let i in classroom){
// console.log(i);
// }
// Output will be : for finding key
// whiteboard
// loops.js:156 chock
// loops.js:156 duster
// loops.js:156 studentcapacity
// loops.js:156 group
// Example : for finding both key with value
// const student = {
// name: "Aditya kumar",
// age : 16,
// cgpa : 8.2,
// isPass : true,
// };
// for(let key in student){
// console.log("Our obedient student whose " + "detail , " + key + " of student = " + student[key]);
// }
// 3. Nested Loops:
// Useful for working with multi-dimensional data structures or generating patterns.
// Example: Generating a multiplication table from 1 to 5.
// console.log("Multiplication Table (1 to 5):");
// for (let row = 1; row <= 5; row++) {
// let rowOutput = "";
// for (let col = 1; col <= 5; col++) {
// rowOutput += (row * col) + "\t"; // '\t' adds a tab for spacing.
// }
// console.log(rowOutput);
// }
// 4. Break and Continue:
// 'break' exits the loop entirely.
// 'continue' skips the current iteration and moves to the next.
// Using break: Exit loop when a condition is met.
// for (let i = 1; i <= 10; i++) {
// if (i === 6) {
// console.log("Breaking the loop at i =", i);
// break; // Exits the loop when i equals 6.
// }
// console.log(`i = ${i}`);
// }
// Using continue: Skip even numbers.
// for (let i = 1; i <= 10; i++) {
// if (i % 2 === 0) { // Check if i is even.
// continue; // Skip this iteration if even.
// }
// console.log(`Odd number: ${i}`);
// }
// -----------------------------
// Asynchronous Looping with Promises (Advanced Concept)
// -----------------------------
// Sometimes you need to perform asynchronous operations (like API calls) in a loop.
// Using async/await inside a loop lets you wait for promises to resolve before continuing.
// Example: Simulate asynchronous operations with a delay.
// async function asyncLoopExample() {
// // A helper function that returns a promise resolved after ms milliseconds.
// const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// for (let i = 1; i <= 5; i++) {
// console.log(`Async operation ${i} started`);
// await delay(1000); // Pause for 1 second before next iteration.
// console.log(`Async operation ${i} finished`);
// }
// }
// asyncLoopExample();
// ============================================
// Conclusion:
// This comprehensive guide covers different loop types in JavaScript:
// - For loops (basic, dynamic limits, and logging intermediate states)
// - While and Do-While loops
// - Specialized loops (for-of and for-in)
// - Nested loops for multi-dimensional operations
// - Loop control using break and continue
// - Handling asynchronous operations within loops using async/await
//
// Understanding these looping constructs enables you to efficiently iterate through data,
// manage complex control flows, and build more advanced asynchronous logic in your applications.
// ============================================