For and For/In Loops
Loops are structures of repetition. If we want to repeat a statement five times, we don't have to write it five times, we just need to run a loop.
We can also use loops to run through the elements of an array. No matter the size of the array, we just need to write the statements once.
For loop
for (var a = 0; a < 5 ; a+=1) {
console.log(a);
}
/* The console will show:
0
1
2
3
4
*/
Note that we just used three statements separated by semicolon to start the loop. The between curly braces we wrote the code to be executed at each iteration of the loop.
Let's understand those three statements inside parenthesis:
- var a = 0: The first statement is executed one time before the loops starts. In this case we start a variable and assign zero to it.
- a < 5: The second statement is a condition that need to return true so the loop continues to be executed. When the condition return false, the loop will stop running.
- a+=1: The third statement is executed at the end of each iteration. In this case we use it to increment the value of the variable on each iteration. This prevents our loop from running forever and killing the browser.
Using the loop to run through the elements of an array
The run throught the elements of an array we'll use its length in the condition:
var students = ['Peter', 'Mary', 'Joseph', 'John', 'Charles'];
for (var a = 0; a < students.length ; a++) {
console.log(students[a]);
}
/* The console will show:
Peter
Mary
Joseph
John
Charles
*/
For/In Loop
The for/in loop comes handy when we need to run through objects, since this kind of data type doesn't have the length property.
O funcionamento dele é bem simples. Consideremos um objeto de alunos, cujas chaves são as matrículas e os valores são os nomes dos alunos.
To initialize this loop we just need to create a variable that will represent each of the objects's properties at each iteration.
var car = {
'Year': 2018,
'Model': 'Evoke',
'Manufacturer': 'Land Rover',
'FuelType': 'Diesel'
}
for (var prop in car) {
console.log( prop + ': ' + car[prop] );
}
/* The console will show:
Year: 2018
Model: Evoke
Manufacturer: Land Rover
FuelType: Diesel
*/
Loops and the getElementBy methods...
Now that we know how loops work, let's change the css of all elements of our page that share a specific class.
<div class="example">Element 1</div>
<div class="example">Element 2</div>
<div class="example">Element 3</div>
var elements = document.getElementsByClassName("example");
for (var a = 0; a < elements.length ; a+=1) {
elements[a].style.color = "orange";
elements[a].style['font-weight'] = "bold";
}
The incremental operator can also be written like: a++.
var elements = document.getElementsByClassName("example");
for (var a = 0; a < elements.length ; a++) {
elements[a].style.color = "orange";
elements[a].style['font-weight'] = "bold";
}