Loops Flashcards

1
Q

How do you write a while loop?

A

let x = 0

while (some condition) {
run this code }

eg:

while (!x = 10) {
console.log(The value is currently ${x})
x++;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

When would you use the ‘break’ keyword?

A

In a while loop.

Use ‘break’ to break out of a while loop if a condition is met.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

When would you use a ‘for… of’ loop?

A

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());
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

When would you use a ‘for… in’ loop?

A

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]
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly