30 Days Of JavaScript.6
Day 6. Loops
Loops
1. for Loop
for(initialization; condition; increment or decrement;){
// code goes here
}
To use a for Loop
, I need three parameters. First I have to initialize a value(a value to start with). Then I have to set a condition. The loop will execute as long as the condition is true. Usually the condition sets the number of times the loop is executed. Lastly, I have to put increment(++) or decrement(–) operator so that the loop will start from initialized value and run the code.
for (let i = 5, i >= 0, i--) {
console.log(i);
}
On the upper code, the parameters inside for
would mean “let i
start from 5. As long as i
is greater or equal to 0, run the code while decrementing i
by one at each execution of the code.”
- Adding all elements in the array
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum = sum + numbers[i]; //sum += numbers[i];
}
console.log(sum);
If I want to add up all the elements, I should declare a new variable for storing the added number(sum
). As the i
is incremented by each iteration, the elements of numbers
will be added to sum
through all its indexes.
About sum += numbers[i]
, I learned it at Day 2 Assignment operators. Remember that the arithmetic operator comes before the equal sign.
I can use this method to add through, say 1 to 10.
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i //same as, sum = sum + i
}
console.log(sum); //55
- Creating a new array based on the existing array
for(let i = 0; i <= 5; i++){
console.log(`${i} * ${i} = ${i * i}`)
}
Using a string template, I can add expressions by using
${}
. Those expressions could be a value, some operations like comparision, arithmetic operation, or ternary operation.
const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland'];
const newArr = [];
for (let i = 0; i < countries.length; i++){
newArr.push(countries[i].toUpperCase());
}
One thing to notice is that the index number starts from zero. So, if I want to run the loop through all the index numbers, I have to initialize i
to zero, and should not include the ending index(< not <=).
On the upper code, push()
was used to fill the newArr
. It adds a new element at the end of an array, so the new elements could be stored in the same order. I thought fill()
could work the same, but it didn’t work. By the way, here’s an article I found about how to fill an array in JavaScript. The code above used the third method, ‘using the push() method in combination with for loop.’
2. while Loop
while (condition) {
statement
}
let i = 0
while (i <= 5) {
console.log(i)
i++
}
// 0 1 2 3 4 5
The while statement is executed as long as the condition evaluates to true(execute the statement as long as i <= 5
is true). The condition is evaluated before executing the statement.
If the condition evaluates to false, the statement is not executed, and code runs after the while loop. Use block statement({}) if there are multiple statements. I can initialize the value before the while loop.
3. do… while Loop
do {
statement
} while (condition);
let i = 0
do {
console.log(i)
i++
} while (i <= 5);
// 0 1 2 3 4 5
The while statement is executed until the condition evaluates to false(execute the statement as long as i <= 5
is true).
The difference of while loop
and do while loop
is that the condition is evaluated after the statement, so at least the statement is executed once. In while loop
, the statement won’t be executed at all if the condition is false. But in do while loop
the statement will still be executed at first even if the condition evaluates to false.
4. for…of Loop
for (const element of arr) {
// code goes here
}
I can use for...of loop
for a loop iterating over iterable objects, including string or array(and more). It is useful when I’m not interested in the index of each element in the array. I think for...or loop
is a good way to declare a variable in an array and return values related, without caring the index numbers.
const webTechs = [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB'
];
for (const tech of webTechs) {
console.log(tech[0]) // get only the first letter of each element, H C J R N M
}
5. break
I’ve seen this one when I was learning about conditionals-switch. Simply put, the break
literally breaks a loop. It stops and interrupt a code from further execution.
for(let i = 0; i <= 5; i++){
if(i == 3){
break; //stop the loop if `i` is 3
}
console.log(i);
}
// 0 1 2
The upper code will execute the iteration until i
reaches 3. If i
is equal to 3, it will terminate the loop and move on to the following statement.
6. continue
It is used to skip a certain iterations. continue()
terminates execution of the statements in the current iteration of the loop, and continues executing loop with the next iteration.
for (let i = 0; i <= 5; i++) {
if (i == 3){
continue; //skip the execution when `i` is 3
}
console.log(i)
}
// 0 1 2 4 5
Leave a comment