2 min read

For Loops - JavaScript

For Loops - JavaScript

For Loops can reduce tens and hundreds of lines of codes into as little as 3 lines. It takes repeated codes and extracts better results. For Loops are handy, if you want to run the same code repeatedly, each time with a different value. It is usually used to extract data from Arrays.

Example

for (start_value; end_value; increment_value) 
{ 
}

The loop is initiated with the word “for” in lowercase and followed by parenthesis (round brackets). Between the brackets, you would find three things. Each separated by a semicolon.

  1. Start Value.
  2. End Value (or condition).
  3. Increment Value.

Start value would be executed once. Only before the beginning of the loop. The End Value defines the condition for the code to run. If this condition is false, the loop will not run.

Exercise

Create a web page to try this, which adds the number 11 to 20 and continues by incrementing both values to present a pattern.

Add the following snippet to a text editor and save it as an HTML file.

<!DOCTYPE HTML> 
<html> 
<head> 
<title>For Loops</title> 
</head> 
<body> 

<script> 
     let answer=0; 
     let start_value = 11; 
     let end_value = 20; 
     for ( start_value; start_value < end_value; start_value++ ) {
          answer = answer + start_value; 
          document.write(answer + ", ");
     }
</script> 
</body> 
</html>

Exercise Explained

The first thing you see in the JavaScript part of the exercise (the javaScript part is the snippet between the <script> and </script> tag) is that we have declared three variables.

The variable answer is to store the answer as it changes and display it to the user.

The variable start_value defines the starting point for the count.

The variable end_value will be used to stop the loop.

As we discussed before, variable vstart_value is the start value for the loop. Though we don’t have to use the start value to define a condition to run the For Loop, we can use the variable. In this case, the condition start_value < end_value means to continue the loop if 0 is less than 20. So, the loop will continue until 0 (the start_value) becomes 20. Hence, to make it happen, the last part in the parenthesis is increasing the 0 or start_value by 1 every time. Like that the loop will continue until the condition is met.

As you can see our task or exercise is to display numbers from 12 to 20, we are using the answer variable to store the increment of the start_value variable. The document.write helps us display or print the result to the browser.

Answer

If you followed the steps given, your answer in the browser would be as follows.

11, 23, 36, 50, 65, 81, 98, 116, 135,

More

If you would like to read more on JavaScript, go through IF Statement.

If you prefer to watch, visit my YouTube channel, and don’t forget to subscribe 🙂