June 23, 2021


TriStudy Provide Free Online Tutorials about Programming languages,Digital Marketing, web designing, online earning, web hosting, WordPress etc

Loops in Javascript

Loops in Javascript

Loops in Javascript

The for statement

JavaScript has two ways to run multiple times the same code. It is primarily used to iterate over objects or arrays. Let’s look at an example:

This will print out the following:

The JavaScript statement has the same syntax as the Java and C statements. It has three parts: initialization— iterator variable I is initialized. We initialize I to 0 in this case.
State-The chain continues to execute as long as the state is met. In this example, we’re checking that I’m under 3.
Increment-a directive that increases the iterator. In our case, we are growing up

To iterate over an array and print out all of its members, we usually use the for statement. Here’s an example:

This prints out the contents of the array:

Notice that we used the length property of an array, which returns the number of members in the array, so we know when to stop iterating.

The while statement

The while statement is a simpler version of the statement that checks whether an expression is true and runs as long as it is true. For example

break and continue statements

The break statement allows to stop the execution of a loop. For example, we can create a loop that loops forever using while(true) and use the break statement to break inside the loop instead by checking that a certain condition was met.

The continuous statement skips the rest of the loop and hops back to the loop end. For example, if we want to use a statement to print only odd numbers, we can do the following: