Loops Flashcards
what’s the difference between for
and for ... of
?
for (initialiser; condition; final expression )
or can express as
for (begin ; condition ; step )
likely to be error prone as there are more conditions to set
for (const item of array)
iterates through each item in an array or iterable object and applies code
what’s the syntax for a for
loop - specifying a piece of code to run a certain number of times? explain each part. give a concrete example
for (initialiser; condition; final expression )
INITIALISER/BEGIN: counts number of times loop has run
can also be declared right in the loop
CONDITION: specifies when the condition turns falsy and the loop should stop running
FINAL EXPRESSION/STEP: instruction to increment/decrement counter variable after each loop to bring it closer to a false condition state
CONCRETE EXAMPLE:
for (let i = 1; i < 10; i++) {…};
when might the standard for
loop be useful over for ... of
?
When we need to iterate over object that supports it and we need to access index position of each item
how can we exit loops?
break;
how can we skip iterations?
continue;
what is the difference between while
and do...while
(syntax, function)?
let i = num
while (cond) {
final expression
}
generally preferred over do while
let i = num do { final expression } while (cond);
only use if you want the code to execute at least once no matter the condition as the cond is evaluated after the code runs
what are 2 function expressions that can be used to also loop through code?
let newArray = collection.map(function)
returns a new away with the changed items after applying a specific code to them
let newArray = collection.filter(function);
returns a new array with just the items that match a given cond
where collection is the array storing multiple items
which loop is recommended for beginners? and why?
for loop
easier to keep track of settings as they’re contained in one place
how do we break out of multiple nested loops at the same time?
using labels - we apply a label to the loop we want to break to (e.g. outer) then call it again later on break outer
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
//code
// if an empty string or canceled, then break out of both loops if (!input) break outer; // (*) // do something with the value... } }
alert(‘Done!’);
what happens if we omit any part of the for loop?
if INITIALISER is omitted
for ( ; i < 5 ; i++);
can do this if we’ve already specified a value to the counter variable first e.g. let i = 0
if CONDITION is omitted
if FINAL EXPRESSION is omitted
for ( ; i < 5 ; i++);
makes the loop identical towhile (i < 3)
if everything is omitted
for ( ;; )
infinite loop
how can we make an infinite loop?
while (true)