Table of contents
Introduction
Hey folks, I hope that you must have read my Day 5 Article on #30DaysOfJs. In case, if you haven't then make sure you give it a read by clicking here.
Loops
In the programming world, whenever we need to perform repetitive tasks, such as printing 0 to 100 numbers in the console, we use different kinds of loops. Some of the most commonly used loops used in JavaScript and other programming languages are:
- for Loop:
Syntax:
// For Loop Structure
for(initialization, condition, increment/decrement){
// Code
}
For Example 1:
for(let i = 0; i <= 5; i++){
console.log(i);
}
// Output:
// 0 1 2 3 4 5
For Example 2:
for(let i = 0; i <= 5; i++){
console.log(`${i} * ${i} = ${i * i}`);
}
// Output:
// 0 * 0 = 0
// 1 * 1 = 1
// 2 * 2 = 4
// 3 * 3 = 9
// 4 * 4 = 16
// 5 * 5 = 25
For Example 3:
const countries = ['India', 'America', 'Canada', 'Norway', 'Iceland']
const newArr = []
for(let i = 0; i < countries.length; i++){
newArr.push(countries[i].toUpperCase())
}
// Output:
// ["INDIA", "AMERICA", "CANADA", "NORWAY", "ICELAND"]
- while Loop: In this Loop the variable i iterates from 0 to 5 and as per its logic, all the numbers get printed in the console.
Syntax:
let i = 0
while (i <= 5) {
console.log(i);
i++
}
// Output:
// 0 1 2 3 4 5
- do while Loop:
Syntax:
let i = 0
do {
console.log(i);
i++
} while (i <= 5)
// Output:
// 0 1 2 3 4 5
- for of Loop: This method is quite easy to use when one wants to iterate through arrays and is not interested in the index of each element in the array.
Syntax:
for (const element of arr) {
// Code
}
For Example:
const numbers = [1, 2, 3, 4, 5]
for (const num of numbers) {
console.log(num);
}
// Output:
// 1 2 3 4 5
for (const num of numbers) {
console.log(num * num)
}
// Output:
// 1 4 9 16 25
// Adding all the numbers in the array
let sum = 0
for (const num of numbers) {
sum = sum + num
}
console.log(sum);
// Output:
// 15
const webTechs = ['MongoDB', 'Express', 'React', 'Node'];
for (const tech of webTechs) {
console.log(tech.toUpperCase())
}
// Output:
// MONGODB EXPRESS REACT NODE
- break: break statements are used to interrupt a process in any given loop.
For Example:
for(let i = 0; i <= 5; i++){
if(i == 3){
break
}
console.log(i)
}
// Output:
// 0 1 2
In the above example, when the loop comes at i = 3, the break statement executes and the iteration process stops.
- continue: continue statement is used whenever we need to skip certain iterations.
For Example:
for(let i = 0; i <= 5; i++){
if(i == 3){
continue
}
console.log(i);
}
// Output:
// 0 1 2 4 5
In the above example, when i comes to position 3 it skips this number and moves forward in the lo.
I hope that you must have found this article quite helpful. If yes, then do give a read to some of my other articles!
Who knows you might become a great programmer ๐ค!