0% found this document useful (0 votes)
7 views8 pages

JavaScript Loop Types Explained

Lesson 4 covers loops in programming, which are control structures that repeat instructions based on conditions, essential in most programming languages. It details various types of loops in JavaScript, including 'for', 'for/in', 'for/of', 'while', and 'do/while', along with their syntax and usage examples. The lesson also discusses variable scope within loops and provides exercises to reinforce learning.

Uploaded by

dadaexcel7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views8 pages

JavaScript Loop Types Explained

Lesson 4 covers loops in programming, which are control structures that repeat instructions based on conditions, essential in most programming languages. It details various types of loops in JavaScript, including 'for', 'for/in', 'for/of', 'while', and 'do/while', along with their syntax and usage examples. The lesson also discusses variable scope within loops and provides exercises to reinforce learning.

Uploaded by

dadaexcel7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

11/21/23, 9:25 AM Lesson-4-Loops – [Link].

com

[Link]

Lesson-4-Loops
Download Lesson

Previous Lesson Next Lesson

A loop in programming is a control structure that allows a set of instructions to be repeated multiple times
based on a specified condition. Loops are used to automate repetitive tasks and efficiently process a
sequence of data or perform a block of code multiple times. They are an essential part of almost all
programming languages.

4.1. Types of Loop


JavaScript supports different kinds of loops.

1. for – loops through a block of code a number of times


2. for/in – loops through the properties of an object
3. for/of – loops through the values of an iterable object
4. while – loops through a block of code while a specified condition is true
5. do/while – also loops through a block of code while a specified condition is true

Loop is mostly used with arrays, therefore, we explained loop on based on arrays in next sections.

4.1.1. Loop “for”


The for statement creates a loop with 3 optional expressions.

Expression 1 is executed (one time) before the execution of the code block.
Expression 2 defines the condition for executing the code block.
Expression 3 is executed (every time) after the code block has been executed.

[Link] 1/15
11/21/23, 9:25 AM Lesson-4-Loops – [Link]

for (expression 1; expression 2; expression 3) {


// code block to be executed
}

Example Code 1:

1 //const is used to declared array


2 const cars = ["Saab", "Volvo", "BMW"]
3
4 //displaying each element by using loop
5 for(let i=0; i<[Link]; i++)
6 [Link](cars[i])

[Link] Expression 1 in “for” Loop


Normally you will use expression 1 to initialize the variable used in the loop (let i = 0). This is not always the
case. JavaScript doesn’t care. Expression 1 is optional. You can initiate many values in expression 1
(separated by comma).

Example Code 2:

1 const cars = ["Saab", "Volvo", "BMW"]


2
3 //displaying each elment by using loop
4 for(let i=0, length=[Link]; i<length; i++)
5 [Link](cars[i])

And you can omit expression 1 (like when your values are set before the loop starts) as you can see in below
code.

Example Code 3:

1 const cars = ["Saab", "Volvo", "BMW"]


2
3 //initialize values for loop
4 let i=0, length=[Link]
5
6 //no expression 1
7 for(; i<length; i++)
8 [Link](cars[i])

Example Code 4: If you don’t know about length of a array, then you can use either “for in” or “for of” loop.
There is another method by using “for” loop that is shown in following code. Output is same just like above.

1 const cars = ["Saab", "Volvo", "BMW"];


2 let i=0
3 for (;cars[i];) {
4 [Link](cars[i])
5 i++
6 }

[Link] 2/15
11/21/23, 9:25 AM Lesson-4-Loops – [Link]

[Link] Expression 2 in “for” Loop


Often expression 2 is used to evaluate the condition of the initial variable. This is not always the case.
JavaScript doesn’t care. Expression 2 is also optional. If expression 2 returns true, the loop will start over
again. If it returns false, the loop will end.

Note: If you omit expression 2, you must provide a break inside the loop. Otherwise the loop will never end.
This will crash your browser. Read about breaks in a later chapter of this tutorial.

Example Code 5:

1 let j=0, v=10


2 for(;;j++){
3 [Link](j)
4 if(j==10)
5 break
6 }

[Link] Expression 3 in “for” Loop


Often expression 3 increments the value of the initial variable. This is not always the case. JavaScript
doesn’t care. Expression 3 is optional. Expression 3 can do anything like negative increment (i–), positive
increment (i = i + 15), or anything else. Expression 3 can also be omitted (like when you increment your
values inside the loop).

Example Code 6:

1 let j=5, v=20


2 for(;;){
3 [Link](j)
4 if(j==10)
5 break
6 j++
7 }

4.1.2. Loop “for in”


The JavaScript for in statement loops through the properties of an Object (object, array and date). Syntax
for this loop is given below.

for (key in object) {


// code block to be executed
}

Note: In case of for...in, the “key” will contain indexes (named-index in case of object and numbered-
indexes in case of array)

Importance of loop “for in” over “for” is that you don’t need to know length of total properties/elements of
objects.

[Link] 3/15
11/21/23, 9:25 AM Lesson-4-Loops – [Link]

Example Code 7: In following code, an object “person” is declared by using const keyword and then all
properties of the objects are displayed by using the loop.

It is noted that let is used declare “x”. It is note necessary to use let. You can use either const or let
according to your requirement. The const is necessary to use at the time of declaration of the object.

1 const person = {fname:"John", lname:"Doe", age:25}


2
3 for (let x in person) {
4 [Link](x) //only property's key would be displayed
5 }

Note: Only enumerable properties are included when using a for...in loop to iterate over an object.
While, non-enumerable properties would not be included. It would be discussed in detail in lesson of
object.

Example Code 8: Following code is just like above but in this case “for in” loop is used for array.

1 const numbers = [45, 4, 9, 16, 25];


2
3 for (let x in numbers) {
4 [Link](x) //only array indexes (0,1,2,3,4,5) would be displayed
5 }

Note: Do not use for in over an Array if you want to access array’s element in an order. By using this loop,
array values may not be accessed in the order you expect. If element’s order is important, then it is better
to use a for loop or a for of loop.

4.1.3. Loop “for of”


The JavaScript for of statement loops through the values of an iterable object. It lets you loop over
iterable data structures such as Arrays, Strings, Maps, NodeLists, and more. Syntax for this loop is given
below.

Note: Importance of loop “for of” over “for” is that you have few conditions related to loop.

Note: Importance of loop “for of” over “for in” is that it is used for many iterable objects but “for in” is only
useful for objects and arrays.

for (key of iterable) {


// code block to be executed
}

Note: In case of for…of, the “key” will contain element value instead of index number. You can use for…in in
case of both array and object but for…of is only useful for array.

Example Code 9: In following code, an array “numbers” is declared by using const keyword and then all
properties of the objects are displayed by using the loop.

Note: If you use “for in” loop here, then result of both codes would be same.

[Link] 4/15
11/21/23, 9:25 AM Lesson-4-Loops – [Link]

1 const numbers = [45, 4, 9, 16, 25];


2
3 for (let x of numbers) {
4 [Link](x)
5 }

Example Code 10: In following code, a string “courseName” is used with loop.

Note: If you use “for in” loop here, then result of both codes would not be same. Error will be generated but
“for in” loop will treat string/any-other-iterable-objects differently.

1 let courseName = "web development"


2
3 for (let x of courseName) {
4 [Link](x)// all letter of above string will be displayed in one column
5 }

4.1.4. Loop “while”


The while loop loops through a block of code as long as a specified condition is true.

Example Code 11: In following code, body of the loop would be executed as long as a variable (i) is less than
10.

1 let i=0
2 while (i < 10) {
3 [Link]("value of i: ", i)
4 i++;
5 }

Note: If you forget to increase the variable used in the loop-body, the loop will never end. This will crash
your browser.

4.1.5. Loop “do while”


The do while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true. Syntax for this
loop is given below

do {
// code block to be executed
}
while (condition)

Example Code 12: The example below uses a do while loop. The loop will always be executed at least once,
even if the condition is false, because the code block is executed before the condition is tested.

This code is just line code 14, but we just use do while loop.

[Link] 5/15
11/21/23, 9:25 AM Lesson-4-Loops – [Link]

1 let i=0
2 do {
3 [Link]("value of i: ", i)
4 i++;
5 }
6 while (i < 10)

Note: If you forget to increase the variable used in the loop-body, the loop will never end. This will crash
your browser.

Example Code 13: Following code will iterate each element by using do while loop without calculating
length of the array. Similar code can be write by using while loop. Such type of code is also discussed in
top of for loop.

1 const cars = ["Saab", "Volvo", "BMW"];


2 let i=0
3 do{
4 [Link](cars[i])
5 i++
6 }
7 while(cars[i])

4.2. Scope of Variable Used in Loop


If you used var type variable (having same name) for both inside and outside loop , then it would be
declared generally. In other words, same memory is used for both outside and inside loop. But in this case,
you can redeclare the variable (normally, it is not allowed) inside loop.

Example Code 14: In this code, same memory is used for var type same-variable in case of inside and
outside of loop. It is noted that variable can be redeclared in side loop.

1 var i=5
2 for(var i=0; i<10; i++){
3 [Link](i) //it will display values from 0 to 9
4 }
5 [Link](i) //it will display value 10 for variable i

But if you used let type, then separate memory is allocated for variables outside and inside loop. See
following code.

Example Code 15:

1 let i=5
2 for(let i=0; i<10; i++){
3 [Link](i) //it will display values from 0 to 9
4 }
5 [Link](i) //it will display value 5 for variable i

[Link] 6/15
11/21/23, 9:25 AM Lesson-4-Loops – [Link]

Note: You cannot change type of declaration inside loop. See example code 8 and 9. Both codes will
generate errors for redeclaration.

Example Code 16: Error of redeclaration for line 1 and 2

1 let i=5
2 for(var i=0; i<10; i++){
3 [Link](i)
4 }
5 [Link](i)

Example Code 17: Error of redeclaration for line 1 and 2

1 var i=5
2 for(let i=0; i<10; i++){
3 [Link](i)
4 }
5 [Link](i)

Exercises

Solve following exercises to enhance your learnt concepts related to this lesson.

1. Write a for loop that counts from 1 to 10 and displays each number in the console.
2. Create an array of your favorite fruits. Use a for loop to iterate through the array and display each fruit
in the console.
3. Write a while loop that counts from 1 to 5 and displays each number in the console.
4. Create an array of numbers from 10 to 1. Use a for loop to iterate through the array in reverse order and
display each number.
5. Write a for loop that counts from 1 to 20. For each number, check if it’s even or odd and display a
message in the console.

Solution for Exercise 1

1 for (let i = 1; i <= 10; i++) {


2 [Link](i);
3 }

Solution for Exercise 2

[Link] 7/15
11/21/23, 9:25 AM Lesson-4-Loops – [Link]

1 const favoriteFruits = ['Apple', 'Banana', 'Orange', 'Grapes', 'Strawberry'];


2
3 for (let i = 0; i < [Link]; i++) {
4 [Link](favoriteFruits[i]);
5 }

Solution for Exercise 3

1 let counter = 1;
2
3 while (counter <= 5) {
4 [Link](counter);
5 counter++;
6 }

Solution for Exercise 4

1 const numbersArray = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];


2
3 // Iterating through the array in reverse order and displaying each number
4 for (let i = [Link] - 1; i >= 0; i--) {
5 [Link](numbersArray[i]);
6 }

Solution for Exercise 5

1 for (let i = 1; i <= 20; i++) {


2 if (i % 2 === 0) {
3 [Link](`${i} is even.`); /* backticks are used */
4 } else {
5 [Link](i+" is odd"); /* concatination is used */
6 }
7 }

Previous Lesson Next Lesson

[Link] 8/15

Common questions

Powered by AI

The 'for' loop in JavaScript is used to execute a block of code repeatedly a specific number of times, usually by counting through a range with a variable that is initialized, tested, and incremented within the loop itself. The 'for/in' loop is used to iterate over the properties of an object, looping through its keys, which include numbered and named indices. This loop does not require knowledge of the length of the object's properties but may not preserve the order of elements in arrays. On the other hand, the 'for/of' loop iterates directly over the values of an iterable object, allowing for an easier traversal of data structures like arrays, strings, and Maps, preserving their order. 'For/of' is preferred for iterables like arrays over 'for/in' because 'for/in' may iterate in unexpected orders .

Using a 'for/in' loop with arrays can lead to unintended consequences due to its behavior of iterating over enumerable properties, including non-numeric properties that may have been manually added. It does not guarantee element order, which can be critical for applications relying on predictable sequence processing. Thus, while it can iterate array indices, using 'for/in' is generally discouraged for arrays, with 'for' or 'for/of' loops being preferred to preserve element order and avoid non-numeric property interference .

When using loops with asynchronous operations, it's important to understand that JavaScript's event loop handles asynchronous callbacks, potentially leading to concurrency issues if not properly managed. Each iteration may commence without waiting for the previous cycle's asynchronous task to complete, leading to unexpected outcomes. Techniques such as using async/await within a loop or leveraging Promise chaining are recommended to ensure asynchronous tasks are executed in the desired order, maintaining expected control and synchronization across iterations .

Omitting expressions in a 'for' loop can lead to peculiar behavior; each of the three components (initialization, condition, increment) is optional. Without an initialization expression, a loop must rely on external variables. Omitting the condition results in an infinite loop unless a 'break' statement is used to exit manually, as the loop will continue without evaluating a terminating condition. Omitting the increment requires managing the counter within the loop body. Handling these omitted parts requires careful attention to ensure loop control, as improper handling can lead to infinite loops or other unexpected behavior .

The 'for/of' loop is often preferred over 'for/in' for iterating arrays because it guarantees the iteration of values in the order they are stored in the array, which 'for/in' cannot provide due to its behavior of iterating over all enumerable properties. 'For/of' directly accesses each element within an iterable, making it more suitable for array iteration where order consistency is important, and it exclusively processes array elements rather than indices .

A 'while' loop is ideal when the number of iterations isn't predetermined and depends on a dynamic condition evaluated in each iteration. This loop is preferable when processing should continue based on real-time conditions rather than a counter. For instance, fetching items from a database until a specific condition is met would benefit from a 'while' loop due to its flexible termination condition, in contrast to a 'for' loop where iterations are generally planned and controlled by a counter variable .

Loop control using 'break' immediately exits the loop regardless of the loop's natural condition, which provides a manual override to the loop's continuation. In contrast, natural termination follows evaluating a condition that defines whether it should proceed. 'Break' is useful for quick exits when certain conditions are met within the loop body, avoiding additional iterations and potentially enhancing efficiency. However, strategic usage is crucial to avoid unwarranted interruptions that could disrupt intended logic .

Variables declared with 'var' within a loop in JavaScript have a function or global scope, meaning they share the same memory space both inside and outside of the loop, and can lead to unintended behavior if re-declared. This contrasts with 'let', which is block-scoped, creating new memory spaces for the variable within the loop. This difference results in 'let' restricting the variable to the loop block, preventing redeclaration errors and clashes with variables outside of the loop. Thus, 'let' offers a safer and more predictable way to manage variables inside loops .

The 'do/while' loop has the advantage of guaranteeing that the loop body executes at least once. This is unlike the 'while' loop, which checks the condition before executing any iteration, posing a risk that the loop might not execute if the condition is initially false. The 'do/while' loop is beneficial in scenarios where initialization or setup actions are required once before the loop structure conditions determine subsequent iterations .

Variable scope is crucial in designing JavaScript loops as it determines variable accessibility and lifespan. 'Var'-declared variables have function scope, potentially leading to shared bounds if re-used within different functions or loops. This can cause side-effects or unexpected behaviors like inadvertent value modifications. On the contrary, 'let' and 'const' provide block-level scoping, encapsulating variables within specific loop iterations or block structures, fostering more robust, error-free loop designs with independent loop-specific variables, preventing unintended exposure outside of their defined scope .

You might also like