Loops Flashcards
How do you write a while loop?
let x = 0
while (some condition) {
run this code }
eg:
while (!x = 10) {
console.log(The value is currently ${x}
)
x++;
}
When would you use the ‘break’ keyword?
In a while loop.
Use ‘break’ to break out of a while loop if a condition is met.
When would you use a ‘for… of’ loop?
To iterate over an array.
let subreddits = [ ‘soccer’, ‘popheads’, ‘cringe’, ‘books’ ];
// With a standard for loop
for (let i = 0; i < subreddits.length; i++) {
console.log(subreddits[i]);
}
//Much cleaner with a for...of loop! for (let sub of subreddits) { console.log(sub); }
//Works with other iterables, like strings! for (let char of 'cockadoodledoo') { console.log(char.toUpperCase()); }
When would you use a ‘for… in’ loop?
To iterate over an object’s keys.
You can print out the corresponding values by using the variable within the for loop as a dynamic key for the object.
Eg:
To print key and value…
for (let prop in winnings) {
console.log(prop)
console.log(winnings[prop]
}