6. Loops and logic#
Loops and logic are fundamental concepts in JavaScript (JS) that allow you to perform repeated actions and make decisions in your code.
6.1. Loops#
Loops
are used to repeat a block of code a number of times or until a certain condition is met. There are several types of loops in JavaScript
6.1.1. for
loop#
The for
loop is used when you know in advance how many times you want to execute a statement or a block of statements.
for (let i = 0; i < 5; i++) {
console.log(`Iteration number: ${i} `);
}
6.1.2. for...of
loop#
The for...of
loop is used to iterate over the values of an iterable object (like an array
).
let arr = [10, 20, 30];
for (let value of arr) {
console.log(value);
}
6.1.3. for...in
loop#
The for...in
loop is used to iterate over the properties of an object
.
let obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
console.log(`${key} : ${obj[key]}`);
}
6.1.4. while
loop#
The while
loop repeats a block of code as long as a specified condition is true.
let i = 0;
while (i < 5) {
console.log("Iteration number" + i);
i++;
}
6.1.5. do... while
loop#
The do...while
loop is similar to the while
loop, but it executes the block of code once before checking the condition.
let i = 0;
do {
console.log("Iteration number" + i);
i++;
} while (i < 5);
6.2. Logic (Conditional Statements)#
Conditional statements allow you to execute different code based on different conditions.
6.2.1. if
statement#
The if statement executes a block of code if a specified condition is true.
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
}
6.2.2. if...else
Statement#
The if…else statement executes one block of code if a condition is true, and another block if it is false.
let x = 10;
if (x > 15) {
console.log("x is greater than 15");
} else {
console.log("x is not greater than 15");
}
6.2.3. else if
Statement#
The else if statement is used to specify a new condition if the first condition is false.
let x = 10;
if (x > 15) {
console.log("x is greater than 15");
} else if (x > 5) {
console.log("x is greater than 5 but not greater than 15");
} else {
console.log("x is 5 or less");
}
6.2.4. switch
statement#
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Another day");
}
6.3. Example Combining Loops and Logic#
Here’s an example that combines a loop and conditional statements:
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
console.log(numbers[i] + " is even");
} else {
console.log(numbers[i] + " is odd");
}
}