Learn Programming Fundamentals
1 Programming Fundamentals
2 Variables Data Types
3 Conditional Structures
4 Strings
5 Arrays
6 Objects
8 Functions
Imagine a scenario where you're required to print the statement "Hello World" a hundred times. Writing a print statement a hundred times can be tedious. What if you could achieve the same outcome with just a few lines of code? That's where loops come in handy, enabling us to write concise code for repetitive tasks.
Loops serve as fundamental control structures in programming languages, enabling you to execute a block of code repeatedly based on a specified condition. They streamline tasks such as printing messages multiple times, iterating through data collections, and performing repetitive operations efficiently.
Imagine needing to print a message a thousand times. Instead of writing one thousand console.log
statements, you can use loops to achieve this more elegantly.
Many programming languages offer various types of loops, including:
Here's a basic structure for a FOR loop:
for (variableInitialization; condition; incrementOrDecrement) { console.log("Message"); }
A FOR loop comprises three parts:
It's similar to declaring and assigning a value to a variable.
for (var i = 1; condition; incrementOrDecrement)
It represents the condition that determines whether the loop continues or terminates. For instance, if you want the loop to print "Hello World" 10 times:
for (var i = 1; i <= 10; incrementOrDecrement)
With each iteration, it checks whether the condition is true. When the condition is false, it terminates the loop.
It defines how the loop variable is updated with each iteration. This could be achieved using increment or decrement operators. For example:
for (var i = 1; condition; incrementOrDecrement)
Increment Operator: If we want to add 1
to i
, we can express it as i = i + 1
. An easier and more concise way to achieve the same result is by using i++
.
Decrement Operator: If we want to subtract 1
from i
, we can write it as i = i - 1
. Similarly, a shorter notation for this operation is i--
.
for (var i = 1; i <= 100; i++) { console.log("Hello World!"); }
This will print the Hello World
message 100 times.
for (var i = 1; i <= 10; i++) { console.log(i); }
for (var i = 10; i > 0; i--) { console.log(i); }
let array = [1, 2, 9, 3, 43, 35, 5, 6]; // Get the length of the array let arrayLength = array.length; for (var i = 0; i < arrayLength; i++) { // Print the value of the array element at index i console.log(array[i]); }
This loop iterates through each element of the array and prints its value.