For loop Flashcards
What is the syntax for a basic for loop in TypeScript?
for (initialization; condition; increment) { // code to execute }
True or False: The initialization section of a for loop is optional in TypeScript.
True
Fill in the blank: In a for loop, the _____ section is executed after each iteration.
increment
What keyword can be used to declare the loop variable in a TypeScript for loop?
let or const
In TypeScript, what is the purpose of the condition in a for loop?
To determine whether to continue executing the loop.
What is the syntax for a “for …of loop” in TypeScript?
let arr = [10, 20, 30, 40]; for (var val of arr) { console.log(val); // prints values: 10, 20, 30, 40 }
What is the purpose of the for…of loop in TypeScript?
The for…of loop is used to iterate over iterable objects such as arrays, strings, and other collections.
True or False: The for…of loop can be used to iterate over the keys of an object.
False
Fill in the blank: The syntax for a for…of loop is ‘for (const ____ of iterable) { }’.
element
Which of the following can be used with a for…of loop?
A) Array
B) Object
C) String
A and C (Array and String)
Write a short code snippet using a for…of loop to print each element of an array.
const arr = [1, 2, 3]; for (const num of arr) { console.log(num); }
What does the for…in loop iterate over in TypeScript?
The for…in loop iterates over the enumerable properties of an object.
True or False: The for…in loop can be used to iterate over arrays in TypeScript.
True, but it’s not recommended due to potential unexpected results.
Fill in the blank: The syntax for a for…in loop is: for (____ in object) { }
variable
Which of the following is a correct example of a for…in loop?
A)for (let key in obj) { console.log(key); }
B) for (obj as key) { console.log(key); }
C) for (let val of obj) { console.log(val); }
A) for (let key in obj) { console.log(key); }
Short Answer: What is a potential drawback of using a for…in loop for iterating over arrays?
It may iterate over properties that are not part of the array, leading to unexpected behavior.