Computer for SEE and NEB

It is a complete SEE and NEB solution for computer science. It includes Computer Fundamentals, Database (SQL), Programming in C QBASIC, CSS, JavaScript, and PHP for beginners.

Breaking

Post Top Ad

Your Ad Spot

Thursday, February 23, 2023

JavaScript 'for' loop



JavaScript 'for' loop





JavaScript is a powerful language that is widely used in web development. One of the fundamental concepts of JavaScript is looping, which is a way to execute a block of code repeatedly. The JavaScript 'for' loop is a popular looping construct, which allows developers to iterate over a set of values and perform operations on them.

In this article, we will explore the JavaScript for loop and how it can be used to execute code repeatedly.

Understanding the 'for' Loop


In JavaScript, a for loop is a control flow statement that allows you to execute a block of code repeatedly based on a set number of iterations or based on specific conditions.

The basic syntax of a for loop is:

for (initialization; condition; increment/decrement) {
// code to be executed
}


i) initialization: This statement is executed before the loop starts. It usually initializes a counter variable that is used to control the number of iterations.

ii) condition: This statement is evaluated before each iteration. If it is true, the loop continues; if it is false, the loop stops.

iii) iteration: This statement is executed at the end of each iteration. It typically increments or decrements the counter variable.

iv) code to be executed: This is the block of code that will be executed repeatedly as long as the condition is true.



Using the for Loop


Let's look at an example to see how the for loop works in practice. Suppose we want to print the numbers from 1 to 10. We can use a for loop to achieve this as follows:



Explanation:

The let i = 1 initializes the loop variable i to 1.

The i <= 10 condition checks if i is less than or equal to 10. If it is true, the loop continues.

The document.write(i) statement prints the value of i to the page.

The i++ increments the value of i by 1 after each iteration.



Output:

Example: 



Output:




Conclusion:

The fundamental concept of JavaScript 'for' loop is widely used in web development. It provides a simple and efficient way to execute a block of code repeatedly. By understanding how the for loop works and how to use it effectively, developers can create more efficient and powerful JavaScript programs.





No comments:

Post a Comment

Post Top Ad

Your Ad Spot

Pages