For Loops in JavaScript
Read This on Github
⭐ Syntax of For Loop
For Loops Syntax Breakdown
for (initialization; condition; increment/decrement) {
// code to be executed
}
Initialization
: This is the first part of the for loop and is used to initialize a loop counter variable. This is usually done by declaring a variable and assigning it a starting value. For example:
let i = 0;
Condition
: This is the second part of the for loop and is used to specify the condition that must be met for the loop to continue running. As long as the condition is true, the loop will continue to execute. When the condition becomes false, the loop will stop. For example:
i < 10
Increment/Decrement
: This is the third part of the for loop and is used to increment or decrement the loop counter variable. For example:
i++
Code to be executed
: This is the code that will be executed as long as the condition is true. For example:
for (let i = 0; i < 10; i++) {
console.log(i);
}
This for loop will print the numbers 0 through 9 to the console.
⭐ Explaining Step by Step of For Loop
For Loops Explained with Example
Now imagine this is our syntax of for loop:
For (statement1; statement2; statement 3){
//code to be executed
}
Now we will explain each statement one by one when and how it will be executed.
✨ 1. Initialization
(statement1): The first step in a for loop is the initialization, which is the first statement inside the for loop. This statement is executed only once, before the loop starts. It is used to initialize a loop counter variable, which is a variable that is used to keep track of the number of times the loop has run.
For example:
for (let i = 0; statement2; statement3) {
// code to be executed
}
In this example, the loop counter variable is i, which is initialized to 0.
✨ 2. Condition
(statement2): The second step in a for loop is the condition, which is the second statement inside the for loop. This statement is evaluated before each iteration of the loop. If the condition evaluates to true, the loop will continue to run. If the condition evaluates to false, the loop will stop running.
For example:
for (statement1; i < 10; statement3) {
// code to be executed
}
In this example, the condition is i < 10, which means that the loop will continue to run as long as i is less than 10.
✨ 3. Code block:
: If the condition is true, the code inside the for loop's code block will be executed. This is the third step in a for loop.
For example:
for (statement1; statement2; statement3) {
console.log(i);
}
In this example, the code block consists of a single line that prints the value of i to the console.
✨ 4. Increment/Decrement
(statement3): The fourth and final step in a for loop is the increment/decrement, which is the third statement inside the for loop. This statement is executed after each iteration of the loop. It is used to update the loop counter variable so that the loop can continue running or stop when the condition is met.
For example:
for (statement1; statement2; i++) {
// code to be executed
}
In this example, the increment/decrement statement is i++, which means that the value of i will be increased by 1 after each iteration of the loop.
😊 Here is an example of a for loop that puts all these steps together:
for (let i = 0; i < 10; i++) {
console.log(i);
}
This for loop will print the numbers 0 through 9 to the console. The loop will start by initializing the loop counter variable i to 0. It will then check the condition i < 10, which will be true because 0 is less than 10. The code inside the loop's code block, which is console.log(i), will be executed, printing the value of i (0) to the console. The increment/decrement statement i++ will then be executed, increasing the value of i by 1. The loop will then repeat, starting with the condition statement again. This process will continue until the value of i becomes 10, at which point the condition i < 10 will be false and the loop will stop.
Initialization (e.g. let i = 0)
Loop:
Condition (e.g. i < 10)
If condition is true:
Code block (e.g. console.log(i))
Increment/decrement (e.g. i++)
Go back to Loop
If condition is false:
Exit loop
⭐ Example of For Loop
For Loops Example for Beginners
✨ 1. Printing the numbers from 1 to 10:
for (let i = 1; i <= 10; i++) {
console.log(i);
}
This for loop will print the numbers 1 through 10 to the console.
✨ 2. Printing the numbers from 10 to 1:
for (let i = 10; i >= 1; i--) {
console.log(i);
}
This for loop will print the numbers 10 through 1 to the console.
✨ 3. Printing the even numbers from 1 to 10:
for (let i = 2; i <= 10; i += 2) {
console.log(i);
}
This for loop will print the even numbers 2, 4, 6, 8, and 10 to the console.
✨ 4. Printing the odd numbers from 1 to 10:
for (let i = 1; i <= 10; i += 2) {
console.log(i);
}
This for loop will print the odd numbers 1, 3, 5, 7, and 9 to the console.
✨ 5. Calculating the sum of the first 10 numbers:
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
console.log(sum);
This for loop will calculate the sum of the first 10 numbers (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10)=55 and print the result to the console.
✨ 6. Calculating the sum of the first 10 even numbers:
let sum = 0;
for (let i = 2; i <= 10; i += 2) {
sum += i;
}
console.log(sum);
This for loop will calculate the sum of the first 10 even numbers (2 + 4 + 6 + 8 + 10)=30 and print the result to the console.
✨ 7. Calculating the sum of the first 10 odd numbers:
let sum = 0;
for (let i = 1; i <= 10; i += 2) {
sum += i;
}
console.log(sum);
This for loop will calculate the sum of the first 10 odd numbers (1 + 3 + 5 + 7 + 9)=25 and print the result to the console.
for (let i = 10; i >= 1; i--) {
console.log(i);
}
This for loop will print the numbers 10 through 1 to the console.
⚡ Playground
This for loop iterates through an array of numbers and calculates the sum of all the even numbers in the array. The loop counter variable i is initialized to 0 and is incremented by 1 after each iteration of the loop. The loop continues to execute as long as i is less than the length of the numbers array. Inside the loop, the current number being processed is stored in the variable currentNumber and is checked to see if it is even (i.e. if it is divisible by 2). If it is even, it is added to the sum variable. When the loop finishes executing, the sum variable will contain the sum of all the even numbers in the numbers array.
I hope this example helps you understand how for loops can be used to perform more complex tasks in JavaScript. Let me know if you have any questions.
💥 for-in-loops in JavaScript
for-in-loops Breakdown
A for-in loop is a looping construct in JavaScript that allows you to iterate over the properties of an object. Here's the syntax for a for-in loop:
?? Syntax of the for-in loop:
for (variable in object) {
// code to be executed
}
The variable is a variable that takes on the value of each property name in the object as the loop iterates. The object is the object whose properties you want to access.
Here's an example of a for-in loop that iterates over the properties of an object:
let person = {
name: 'John',
age: 30,
job: 'teacher'
};
for (let prop in person) {
console.log(prop + ': ' + person[prop]);
}
This would output the following:
name: John
age: 30
job: teacher
Note that the for-in loop will iterate over all enumerable properties of the object, including inherited properties. If you only want to iterate over the object's own properties, you can use the Object.keys() method to get an array of the object's own enumerable properties, and then use a for-of loop to iterate over the array:
for (let prop of Object.keys(person)) {
console.log(prop + ': ' + person[prop]);
}
It's also important to note that the order in which the properties are iterated is not guaranteed and may vary from one browser to another. If you need to iterate over the properties in a specific order, you can use an array of objects with the desired order, and then use a for-of loop to iterate over the array.
⚡ Playground
💥 for-of-loops in JavaScript
for-of-loops Breakdown
A for-of loop is a looping construct in JavaScript that allows you to iterate over the elements of an iterable object, such as an array or a string. Here's the syntax for a for-of loop:
?? Syntax of the for-in loop:
for (variable of iterable) {
// code to be executed
}
The variable is a variable that takes on the value of each element in the iterable object as the loop iterates. The iterable object is the object whose elements you want to access.
Here's an example of a for-of loop that iterates over the elements of an array:
let colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(color);
}
This would output the following:
red
green
blue
You can also use a for-of loop to iterate over the characters of a string:
let message = 'Hello World';
for (let char of message) {
console.log(char);
}
This would output the following:
H
e
l
l
o
W
o
r
l
d
Note that the for-of loop is only designed to work with iterable objects, so you cannot use it to iterate over the properties of an object like you can with a for-in loop. If you want to iterate over the properties of an object, you can use a for-in loop or use the Object.keys() method to get an array of the object's own enumerable properties, and then use a for-of loop to iterate over the array.
⚡ Playground
⁉️ Basic Differences
Basic Differences between
for-in and for-of loops
for-in loop | for-of loop | |
---|---|---|
Purpose | Iterate over the properties of an object | Iterate over the elements of an iterable object |
Syntax | for (variable in object) { ... } | for (variable of iterable) { ... } |
Iteration variable | Property name | Element value |
Applicable to | Objects | Iterable objects |
Inherited properties | Included | Excluded |
Order of iteration | Not guaranteed | As specified by the iterable object |
let is block-scoped, while var is function-scoped.
for (var i = 0; i < 5; i++) {
console.log(i); // 0 1 2 3 4
}
console.log(i); // 5
for (let j = 0; j < 5; j++) {
console.log(j); // 0 1 2 3 4
}
console.log(j); // ReferenceError: j is not defined
In the example above, the i variable declared with var is available outside the for loop and has a value of 5 after the loop has completed. On the other hand, the j variable declared with let is only available inside the for loop and is not defined outside the loop, causing a ReferenceError when it is accessed.
Note: In general, it is recommended to use let rather than var when declaring variables, as let provides better control over the scope of a variable and can help to avoid potential issues such as variable hoisting and unintended side effects.
- Check out the above example to see the difference between var and let(check the console).
📚 Extra
An infinite loop is a loop that runs indefinitely, unless it is interrupted by some external factor. Here is an example of an infinite loop using a for loop in JavaScript:
for (;;) {
console.log("Hello, world!");
}
This loop will continue to print "Hello, world!" to the console indefinitely.
The for loop in JavaScript has three parts: the initialization, the condition, and the increment. In the example above, the initialization and increment are both left blank, so they do not do anything. The condition is also left blank, which means that it is always true, so the loop will never end.
Here is an example of a for loop with all three parts specified:
for (let i = 0; i < 10; i++) {
console.log(i);
}
This loop will initialize the variable i to 0, and then it will run the loop as long as i is less than 10. After each iteration of the loop, it will increment i by 1. This loop will print the numbers 0 through 9 to the console, and then it will stop because i is no longer less than 10.
if the condition of the for loop is set to Infinity, then the loop will run indefinitely. Here is an example of how you might use this to create an infinite loop:
for (var i = 0; i < Infinity; i++) {
console.log("Hello, world!");
}