JavaScript provides several looping mechanisms to help you execute repetitive tasks efficiently. Here, we will cover all aspects of the for
statement, do...while
statement, while
statement, for...in
statement, for...of
statement, and the use of break
and continue
statements, including labeled statements.
The for
Statement
The for
loop is the most traditional loop in JavaScript, often used for iterating over arrays and executing code a fixed number of times.
Syntax
for (initialization; condition; increment) {
// code block to be executed
}
Initialization: Initialize the loop counter variable.
Condition: Defines the condition for the loop to run.
Increment: Increase the counter each time the code block in the loop has been executed.
Example
for (let i = 0; i < 5; i++) {
console.log("The number is " + i);
}
Detailed Example
let fruits = ["apple", "banana", "mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Explanation
Initialization:
let i = 0
sets up the counter variable.Condition:
i < fruits.length
ensures the loop runs whilei
is less than the length of the array.Increment:
i++
incrementsi
after each iteration.
Nested for
Loops
Nested for
loops are loops inside loops.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(matrix[i][j]);
}
}
Explanation
Outer Loop: Iterates over rows.
Inner Loop: Iterates over columns within each row.
The do...while
Statement
The do...while
loop guarantees that the block of code inside the loop will execute at least once before checking the condition.
Syntax
do {
// code block to be executed
} while (condition);
Example
let i = 0;
do {
console.log("The number is " + i);
i++;
} while (i < 5);
Detailed Example
let password;
do {
password = prompt("Enter the password:");
} while (password !== "12345");
alert("Access granted");
Explanation
Execution: The code inside
do
executes at least once.Condition Check: After execution, the
while
condition is checked.
The while
Statement
The while
loop executes a block of code as long as the specified condition is true
.
Syntax
while (condition) {
// code block to be executed
}
Example
let i = 0;
while (i < 5) {
console.log("The number is " + i);
i++;
}
Detailed Example
let n = 0;
let x = 0;
while (n < 3) {
n++;
x += n;
console.log(`n: ${n}, x: ${x}`);
}
Explanation
Initialization:
let n = 0
andlet x = 0
are initialized.Condition Check:
while (n < 3)
checks the condition.Increment and Accumulation:
n++
incrementsn
andx += n
addsn
tox
.
The for...in
Statement
The for...in
loop is used to iterate over the properties of an object.
Syntax
for (variable in object) {
// code block to be executed
}
Example
const person = { fname: "John", lname: "Doe", age: 25 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
Detailed Example
const car = { brand: "Toyota", model: "Corolla", year: 2020 };
for (let property in car) {
console.log(property + ": " + car[property]);
}
Explanation
Iteration: The loop iterates over each property in the object.
Accessing Values:
car[property]
accesses the value associated with each property.
Considerations
- Inherited Properties: The
for...in
loop iterates over all enumerable properties, including inherited ones. To avoid this, usehasOwnProperty
method.
for (let key in car) {
if (car.hasOwnProperty(key)) {
console.log(key + ": " + car[key]);
}
}
The for...of
Statement
The for...of
loop is used to iterate over iterable objects like arrays, strings, and more.
Syntax
for (variable of iterable) {
// code block to be executed
}
Example
const numbers = [1, 2, 3, 4, 5];
for (let num of numbers) {
console.log(num);
}
Detailed Example
const languages = ["JavaScript", "Python", "Java"];
for (let language of languages) {
console.log("I love " + language);
}
Explanation
Initialization:
const numbers = [1, 2, 3, 4, 5]
sets up the array.Iteration: The loop iterates over each element in the array.
Iterating Over Strings
const string = "JavaScript";
for (let char of string) {
console.log(char);
}
Explanation
Initialization:
const string = "JavaScript"
sets up the string.Iteration: The loop iterates over each character in the string.
The break
and continue
Statements
The break
Statement
The break
statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
Example
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log("The number is " + i);
}
Explanation
Condition Check:
if (i === 5)
checks the condition.Break:
break
terminates the loop wheni
equals 5.
The continue
Statement
The continue
statement skips the current iteration of the loop and continues with the next iteration.
Example
for (let i = 0; i < 10; i++) {
if (i === 5) {
continue;
}
console.log("The number is " + i);
}
Explanation
Condition Check:
if (i === 5)
checks the condition.Continue:
continue
skips the iteration wheni
equals 5 and continues with the next iteration.
Labeled Statements
Labeled statements provide a way to break or continue nested loops. A label is an identifier followed by a colon (:
) that precedes a statement.
Syntax
labelName: {
// code block
}
Example
outerLoop: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop;
}
console.log("i = " + i + ", j = " + j);
}
}
Explanation
Label Definition:
outerLoop:
defines the label.Break with Label:
break outerLoop
breaks out of the labeled loop.
Detailed Example
outerLoop: for (let i = 0; i < 3; i++) {
innerLoop: for (let j = 0; j < 3; j++) {
if (j === 2) {
continue outerLoop;
}
console.log("i = " + i + ", j = " + j);
}
}
Explanation
Label Definition:
outerLoop:
andinnerLoop:
define the labels.Continue with Label:
continue outerLoop
skips the current iteration ofouterLoop
whenj
equals 2.
Practical Use Case
Using labeled statements can be beneficial when dealing with complex nested loops where you need precise control over which loop to break or continue.
search: {
for (let i = 0; i < array1.length; i++)
{
for (let j = 0; j < array2.length; j++) {
if (array1[i] === array2[j]) {
console.log("Found common element: " + array1[i]);
break search;
}
}
}
console.log("No common elements found");
}
Explanation
Label Definition:
search:
defines the label.Break with Label:
break search
exits both loops when a common element is found.
Conclusion
Mastering loops and iterations in JavaScript is crucial for handling repetitive tasks efficiently. Each loop—for
, do...while
, while
, for...in
, and for...of
—serves unique purposes and offers different advantages depending on the scenario. Additionally, understanding how to use break
and continue
statements, along with labeled statements, provides greater control over loop execution, particularly in complex nested loops. With these tools in your programming arsenal, you'll be well-equipped to write more efficient and readable code.
In our next article, we'll dive deeper into JavaScript control flow by exploring conditional statements and exception handling. These essential concepts will further enhance your ability to manage the logic and error handling in your programs, ensuring robust and reliable code. Stay tuned!