Loops - patrickcole/learning GitHub Wiki
Loops
For Loop
- The traditional
for
loop. - We start with a initial state (ex:
let i = 0
) - Next, a conditional statement, that while still true will continue to execute the loop; if false, it will stop executing the loop
- Finally, what happens at the end of each step of the loop (ex:
i++
or "increase the value ofi
by1
)
const vaughnHello = ['hey','sup','greetings'];
for ( let i = 0; i < vaughnHello.length; i++ ) {
console.log(vaughnHello[i]);
}
// => "hey"
// => "sup"
// => "greetings"
// "That guy always says hi three different ways"
for...in
Used for looping through items that are enumerables
, or items that are "being counted one at a time. This means the collection's elements can be distinctly identified and referenced." (Mehraban, dev.to - Apr. 24, 2020)
const vehicle = {
color: 'black',
type: 'sedan',
year: '2017',
make: 'Honda',
model: 'Civic LX'
}
for ( let key in vehicle ) {
console.log(`${key}: ${vehicle[key]}`);
}
// => "color: black"
// => "type: sedan"
// => "year: 2017"
// => "make: Honda",
// => "model: Civic LX"
for...in
can be used on other enums such as anArray
orString
. However, you cannot usefor...in
onSymbol
s.
for...of
Applies to iterable
objects. Objects where an action is repeated on each item of the iterable.
const stock = [3,10,49];
for ( let amount of stock ) {
console.log(`Amount of each item: ${amount}`);
}
// => "Amount of each item: 3"
// => "Amount of each item: 10"
// => "Amount of each item: 49"
Can also be used with
String
const greeting = "Hello";
for ( let char of greeting ) {
console.log(char);
}
// => "H"
// => "e"
// => "l"
// => "l"
// => "o"