For Loop

Loops are an essential concept in programming, and they allow you to execute a block of code repeatedly until a certain condition is met. JavaScript has several types of loops.

The for loop is the most commonly used loop in JavaScript, and it is used to execute a block of code a specified number of times. Here is the basic syntax of the for loop:

Loading Code . . .
  • The initialization statement is executed only once at the beginning of the loop, and it is used to initialize the loop counter variable.
  • The condition is evaluated at the beginning of each iteration of the loop, and if it is true, the loop code is executed. If it is false, the loop is terminated.
  • The increment/decrement statement is executed at the end of each iteration of the loop, and it is used to update the loop counter variable.

Here is an example of a for loop that prints the numbers from 1 to 10:

Loading Code . . .

This loop starts with i equal to 1, checks if i is less than or equal to 10, and then increments i by 1 after each iteration. The loop will run 10 times, and will print the numbers from 1 to 10 to the console.


Be aware of infinite loops!

Infinite loops are a common problem that can occur when writing loops. An infinite loop is a loop that never stops executing its instructions and continues running indefinitely.

Infinite loops can cause your program to become unresponsive or crash, and they can also consume a large amount of system resources, such as CPU time and memory.

One common cause of infinite loops is when the loop's termination condition is not correctly defined or is never reached. For example, if you forget to update the loop variable in a for loop or if the termination condition is always true, the loop will run indefinitely.

Here is an example of an infinite loop:

Loading Code . . .

In this example, the loop will keep running while i is less than or equal to 10, but the loop variable is being decremented by 1 on each iteration, so i will never be greater than 10. This means that the loop will never terminate, and it will run forever.


In the code below we have a variable first and another last with a start number and an end number.

Run console.log() to list all numbers between first and last.

Loading...
Loading...

© 2024 - ®Mewters