[Go to site: main page, start]

0% found this document useful (0 votes)
58 views6 pages

JavaScript For Loop Overview

JavaScript loops allow code to be executed repeatedly. The for loop iterates over a block of code a specified number of times. It has three optional statements - initialization of a counter variable, condition to be met, and incrementing of the counter. This allows looping through elements of an array more easily than individually accessing each element. Other loop types include for/in to iterate object properties, for/of to iterate iterable objects, while to loop based on a condition being true, and do/while to loop at least once even if condition is false.

Uploaded by

oussama
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)
58 views6 pages

JavaScript For Loop Overview

JavaScript loops allow code to be executed repeatedly. The for loop iterates over a block of code a specified number of times. It has three optional statements - initialization of a counter variable, condition to be met, and incrementing of the counter. This allows looping through elements of an array more easily than individually accessing each element. Other loop types include for/in to iterate object properties, for/of to iterate iterable objects, while to loop based on a condition being true, and do/while to loop at least once even if condition is false.

Uploaded by

oussama
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

1/16/2021 JavaScript for Loop

  HTML CSS MORE  EXERCISES   


[Link] LOG IN

Diversified Machine Choices. China & Europe


GET QUOTE
Tech, Trusted by Big Names. Get a Quote Now

JavaScript For Loop


❮ Previous Next ❯

Loops can execute a block of code a number of times.

JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each time with
a different value.

Often this is the case when working with arrays:

Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";

You can write:


var i;
for (i = 0; i < [Link]; i++) {

[Link] 1/12
1/16/2021 JavaScript for Loop

text += cars[i] + "<br>";


  HTML CSS MORE  EXERCISES   
}

Try it Yourself »

Different Kinds of Loops


JavaScript supports different kinds of loops:

for - loops through a block of code a number of times


for/in - loops through the properties of an object
for/of - loops through the values of an iterable object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true

The For Loop


The for loop has the following syntax:

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


// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

Example

for (i = 0; i < 5; i++) {


text += "The number is " + i + "<br>";
}

[Link] 2/12
1/16/2021 JavaScript for Loop

 Try
it Yourself
HTML » CSS MORE  EXERCISES   

From the example above, you can read:

Statement 1 sets a variable before the loop starts (var i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5).

Statement 3 increases a value (i++) each time the code block in the loop has been
executed.

Power BI Training from an


MVP
Learn Power BI from the Best
Start your Power BI journey today with top-
level training for less than half the price.
[Link]

OPEN

Statement 1
Normally you will use statement 1 to initialize the variable used in the loop (i = 0).

This is not always the case, JavaScript doesn't care. Statement 1 is optional.

You can initiate many values in statement 1 (separated by comma):

Example
for (i = 0, len = [Link], text = ""; i < len; i++) {
text += cars[i] + "<br>";
}

[Link] 3/12
1/16/2021 JavaScript for Loop

 Try
it Yourself
HTML » CSS MORE  EXERCISES   

And you can omit statement 1 (like when your values are set before the loop starts):

Example
var i = 2;
var len = [Link];
var text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}

Try it Yourself »

Statement 2
Often statement 2 is used to evaluate the condition of the initial variable.

This is not always the case, JavaScript doesn't care. Statement 2 is also optional.

If statement 2 returns true, the loop will start over again, if it returns false, the loop will
end.

If you omit statement 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.

Statement 3
Often statement 3 increments the value of the initial variable.

This is not always the case, JavaScript doesn't care, and statement 3 is optional.

[Link] 4/12
1/16/2021 JavaScript for Loop

Statement 3 can do anything like negative increment (i--), positive increment (i = i +


15),  HTML CSS MORE  EXERCISES   
or anything else.

Statement 3 can also be omitted (like when you increment your values inside the loop):

Example

var i = 0;
var len = [Link];
for (; i < len; ) {
text += cars[i] + "<br>";
i++;
}

Try it Yourself »

The For/In Loop


The JavaScript for/in statement loops through the properties of an object:

Example
var person = {fname:"John", lname:"Doe", age:25};

var text = "";


var x;
for (x in person) {
text += person[x];
}

Try it Yourself »

The For/Of Loop


[Link] 5/12
1/16/2021 JavaScript for Loop

The JavaScript for/of statement loops through the values of an iterable objects.
  HTML CSS MORE  EXERCISES   
for/of lets you loop over data structures that are iterable such as Arrays, Strings,
Maps, NodeLists, and more.

The for/of loop has the following syntax:

for (variable of iterable) {


// code block to be executed
}

variable - For every iteration the value of the next property is assigned to the variable.
Variable can be declared with const , let , or var .

iterable - An object that has iterable properties.

Looping over an Array

Example
var cars = ["BMW", "Volvo", "Mini"];
var x;

for (x of cars) {
[Link](x + "<br >");
}

Try it Yourself »

Looping over a String

Example

var txt = "JavaScript";


var x;

for (x of txt) {

[Link] 6/12

Common questions

Powered by AI

A 'do/while' loop in JavaScript executes a block of code at least once before checking the condition. This differs from a 'while' loop, which checks the condition before executing the block, potentially skipping the code block completely if the condition is not met initially. The 'do/while' loop is more suitable when the block of code needs to be executed at least once, regardless of the condition. For instance, it would be useful in a situation where user input is to be validated, and the prompt needs to appear at least once. Example use case: ```do { userInput = prompt('Enter a number greater than 10:'); } while (userInput <= 10);``` Here, the prompt will be shown at least once to collect user input and will continue until the requirement is met .

A 'for/in' loop can be inefficient when used with arrays in JavaScript since it iterates over all enumerable properties, including prototype properties, leading to potential performance issues and unintended property access. This inefficiency is particularly pronounced with large datasets where only the array elements need to be accessed. A more efficient alternative is the 'for' loop or the 'for/of' loop. The 'for' loop provides direct index-based access, allowing for efficient iteration without accessing non-element properties. The 'for/of' loop provides a simple and clean way to access element values directly without dealing with array indices, avoiding prototype property pitfalls entirely .

The 'for' loop is used to execute a block of code a certain number of times with a specified initialization, condition, and incrementation. It is most commonly used with arrays. For example, you can loop through an array and perform operations on each element. The 'for/in' loop, on the other hand, is used to loop through the properties of an object, iterating over all the enumerable properties of the object itself and those it inherits from its prototype chain. This is generally used for objects rather than arrays, as the order of iteration in 'for/in' comes from the order of properties in the object. Therefore, 'for' loops are preferable when the sequence of iteration is important, while 'for/in' loops are used to inspect object properties .

Omitting the third statement in a JavaScript 'for' loop, which is typically used to modify the loop variable (e.g., incrementing or decrementing it), can lead to infinite loops if the loop variable is not updated within the loop body. This can cause the browser to crash or become unresponsive. To mitigate this, the developer should ensure that the loop variable is appropriately incremented or decremented within the loop’s block, for instance, through a manual increment statement at the end of the loop body. Example mitigation: ```for (let i = 0; i < x.length; ) { performAction(x[i]); i++; }``` This practice prevents infinite loops by ensuring that each iteration will eventually meet a termination condition .

When the condition statement in a JavaScript 'for' loop is omitted, the loop will continue executing indefinitely unless interrupted, leading to infinite loops which can crash the browser or system due to resource exhaustion. To execute the loop correctly without a condition, a 'break' statement must be included within the loop body to provide a manual exit condition. Without this, the loop lacks a defined stopping condition, leading to non-terminating execution. Implementing conditional logic in the loop's block that checks for a specific state or condition and executes a 'break' is essential for proper loop completion .

The type of variable declaration ('var', 'let', or 'const') used within a JavaScript loop affects its scope and lifetime. 'Var' has function-level scope, which means that the variable can leak out of the loop, affecting code outside its immediate block scope. 'Let' and 'const', however, offer block-level scoping, which restricts the variable's access to the block in which it is declared, preventing conflicts with variables of the same name outside this scope. 'Const' additionally prevents the reassignment of the variable, which can be beneficial for constant values that should not change through the iterations. Choosing between these declarations depends on whether the variable will be modified or reused later in the program and whether its visibility and modification potential need to be controlled .

The 'for/of' loop is specifically designed to iterate over the values of iterable objects, such as arrays, strings, and node lists, allowing access to each value directly. This loop does not iterate over object properties or keys, making it ideal for array iterations where direct access to each element is needed. 'For/in' loops, however, are designed to iterate over the keys of an object, including those of arrays, but this can result in iterating over inherited properties and enumerable properties, which can be inefficient for arrays and result in unexpected behavior. Thus, 'for/of' loops are more efficient and appropriate for array iteration because they avoid the unwanted enumeration of non-index properties and make the code cleaner and more intuitive .

In JavaScript, the scope of variables declared with 'var', 'let', or 'const' significantly impacts a loop's behavior, particularly concerning block scope. 'Var' is function-scoped, meaning variables declared with 'var' can leak out of the loop block, potentially leading to conflicts or unexpected behavior if a variable of the same name is used elsewhere. 'Let' and 'const', being block-scoped, restrict the variable's accessibility to within the loop, helping prevent such issues. This makes 'let' and 'const' preferred in loop constructs to avoid leaking variables, which can result in bugs or logic errors when 'var' is inadvertently reassigned or unintentionally accessed outside the intended loop context .

In JavaScript, a 'for' loop typically consists of three expressions: initialization, condition, and incrementation. All three statements are optional. Omitting the initialization and incrementation allows for more flexible initial conditions and updates, such as if values are set and changed before and within the loop body. If the condition (second statement) is omitted, JavaScript requires that the loop have an internal mechanism to break out of it, usually through a 'break' statement, to prevent infinite loops that can crash the browser. This means you must include a terminating condition inside the loop body to ensure proper execution .

Initializing multiple variables in the first statement of a 'for' loop allows for the simultaneous setup of several loop-related variables, potentially simplifying setup before the loop begins. This functionality can be beneficial in scenarios where multiple conditions need to be tracked or when working with multi-dimensional arrays, such as iterating over a matrix where both row and column indices need to be controlled. This approach consolidates initialization, making the code more organized and easier to understand. Example usage: ```for (let i = 0, j = 10; i < 10 && j > 0; i++, j--) { console.log(i, j); }``` This code logs paired increments and decrements of 'i' and 'j', demonstrating concurrent variable control .

You might also like