JavaScript tutorials for Beginners – JavaScript for loop

 

 

(JavaScript Tutorials for Beginners)

In this end-to-end example, you will learn – JavaScript tutorials for Beginners – JavaScript for loop.

 

JavaScript for loop

In this tutorial, you will learn about the loops and about for loops in JavaScript with the help of examples.

In programming, loops are used to repeat a block of code.

For example, if you want to show a message 100 times, then you can use a loop. It’s just a simple example; you can achieve much more with loops.

This tutorial focuses on JavaScript for loop. You will learn about the other type of loops in the upcoming tutorials.


JavaScript for loop

The syntax of the for loop is:

for(initialExpression; condition; updateExpression) {
    // for loop body
}

Here,

  1. The initialExpression initializes and/or declares variables and executes only once.
  2. The condition is evaluated.
    • If the condition is false, the for loop is terminated.
    • if the condition is true, the block of code inside of the for loop is executed.
  3. The updateExpression updates the value of initialExpression when the condition is true.
  4. The condition is evaluated again.This process continues until the condition is false.

To learn more about the conditions, visit JavaScript Comparison and Logical Operators.


Working of for loop in JavaScript with flowchart
Flowchart of JavaScript for loop

Example 1: Display a Text Five Times

// program to display text 10 times
let n = 5;

// looping from i = 1 to 5
for (let i = 1; i <= n; i++) {
    console.log(`I love JavaScript.`);
}

Output

I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.

Here is how this program works.

Iteration Variable Condition: i <= n Action
1st i = 1
n = 5
true I love JavaScript. is printed.
i is increased to 2.
2nd i = 2
n = 5
true I love JavaScript. is printed.
i is increased to 3.
3rd i = 3
n = 5
true I love JavaScript. is printed.
i is increased to 4.
4th i = 4
n = 5
true I love JavaScript. is printed.
i is increased to 5.
5th i = 5
n = 5
true I love JavaScript. is printed.
i is increased to 6.
6th i = 6
n = 5
false The loop is terminated.

Example 2: Display numbers from 1 to 5

// program to display numbers from 1 to 5
let n = 5;

// looping from i = 1 to 5
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++) {
    console.log(i);     // printing the value of i
}

Output

1
2
3
4
5

Here is how this program works.

Iteration Variable Condition: i <= n Action
1st i = 1
n = 5
true 1 is printed.
i is increased to 2.
2nd i = 2
n = 5
true 2 is printed.
i is increased to 3.
3rd i = 3
n = 5
true 3 is printed.
i is increased to 4.
4th i = 4
n = 5
true 4 is printed.
i is increased to 5.
5th i = 5
n = 5
true 5 is printed.
i is increased to 6.
6th i = 6
n = 5
false The loop is terminated.

Example 3: Display Sum of n Natural Numbers

// program to display the sum of natural numbers
let sum = 0;
let n = 100

// looping from i = 1 to n
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++) {
    sum += i;  // sum = sum + i
}

console.log('sum:', sum);

Output

sum: 5050

Here, the value of sum is 0 initially. Then, a for loop is iterated from i = 1 to 100. In each iteration, i is added to sum and its value is increased by 1.

When i becomes 101, the test condition is false and sum will be equal to 0 + 1 + 2 + … + 100.


The above program to add sum of natural numbers can also be written as

// program to display the sum of n natural numbers
let sum = 0;
let n = 100;

// looping from i = n to 1
// in each iteration, i is decreased by 1
for(let i = n; i >= 1; i-- ) {
    // adding i to sum in each iteration
    sum += i; // sum = sum + i
}

console.log('sum:',sum);

This program also gives the same output as the Example 3. You can accomplish the same task in many different ways in programming; programming is all about logic.

Although both ways are correct, you should try to make your code more readable.


JavaScript Infinite for loop

If the test condition in a for loop is always true, it runs forever (until memory is full). For example,

// infinite for loop
for(let i = 1; i > 0; i++) {
    // block of code
}

In the above programs, the condition is always true which will then run the code for infinite times.


In the next tutorial, you will learn about while and do...while loop.

 

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!

 

JavaScript tutorials for Beginners – JavaScript while and do…while Loop

Pandas Example – Write a Pandas program to remove infinite values from a given DataFrame

Learn Java by Example: Java Program to Calculate the Sum of Natural Numbers