"For" deck Flashcards
for..in used with Objects?
Yes
for..in used with Arrays?
Yes, not advised
for..in used with Strings
Yes, not advised
for..of used with Objects?
No
for..of used with Arrays?
Yes
for..of used with Strings
Yes
const obj = { a: 1, b: 2, c: 3, d: 4 }
WRITE A FOR..IN LOOP
// Result: 1, 2, 3, 4
for (var property1 in object1) {
console.log(object1[property1]);
}
Write a blank for in loop
for (variable in enumerable) { // do stuff }
const array = [‘a’, ‘b’, ‘c’, ‘d’];
Write a for loop
// Result: a, b, c, d
for (let i = 0; i < array.length; i++) { console.log(array[i]); }
The for..of loop doesn’t work with Objects because they are not ________ and therefore don’t have a [Symbol.iterator] property.
“iterable”,
The for..of loop doesn’t work with_________ because they are not “iterable”, and therefore don’t have a [Symbol.iterator] property.
Objects
The for..of loop works well with________ and_________, as they are iterable. This method is a more reliable way of looping through an Array in sequence.
Arrays
Strings
it is generally advised that _________not be used with Arrays, particularly because it cannot be guaranteed that the iteration happens in sequence, which is usually important for Arrays
for..in
let iterable = [10, 20, 30];
write for..of
// 10 // 20 // 30
for (const value of iterable) {
console.log(value);
}
let iterable = ‘boo’;
write for..of
// "b" // "o" // "o"
for (let value of iterable) {
console.log(value);
}
var string1 = ""; var object1 = {a: 1, b: 2, c: 3};
write a for in
console.log(string1); // expected output: "123"
for (var property1 in object1) {
string1 += object1[property1];
}
__________ should not be used to iterate over an Array where the index order is important.
for…in
for…in should not be used to iterate over an_______ where the index order is important.
Array
var fruits =[“apple”, “pear”, “plum”];
use for Each to interate in console.
fruits.forEach(fruit => console.log(fruit));
the for Each loop cannot _________ of loops like the for loop
break