While & For Loops
JavaScript Fundamentals: While & For Loops (??)
In Simple terms, what are loops used for in JavaScript?
View Answer:
Interview Response: Loops are a way to repeat or iterate over the same code multiple times.
Explain how a while loop works?
View Answer:
Interview Response: The while loop iterates if a given condition is met and exits the loop when the condition no longer exists.
Technical Response: A while loop is an iterative body that loops while a specified condition remains true.
Code Example:
let i = 0;
while (i < 3) {
// shows 0, then 1, then 2
alert(i);
i++;
}
What is the definition of an iteration in a JavaScript loop?
View Answer:
Interview Response: A single execution of the loop body is called an iteration in software engineering.
Code Example: Below, we see three iterations in the while loop body.
let i = 1;
while (i < 3) {
// shows 1, then 2, then 3
alert(i);
i++;
}
Does a while loop require an explicit incrementor?
View Answer:
Interview Response: Yes, a while loop requires an explicit incrementor to maintain a controlled iteration.
Technical Response: Yes, the incrementor is required to continue the iterations. If it is missing, then the process is killed immediately after the first iteration or can result in an endless loop. This process all depends on whether you are incrementing or decrementing the loop.
Code Example:
let i = 3;
while (i) {
// shows 0, then 1, then 2
alert(i);
i--; // if the incrementor (i--) is missing then it results in an endless loop.
}
Are curly brackets required in a single-line loop body?
View Answer:
Interview Response: No, If the loop body has a single statement, we can omit the curly braces.
Code Example:
let i = 3;
while (i) alert(i--);
What is the difference between Do-While and While Loop?
View Answer:
Interview Response: The do-while loop conditional check is at the end of the loop. In a while loop, the condition is at the beginning of the loop.
Code Example:
do {
// loop body
} while (condition);
Explain, How the Do-While loop works?
View Answer:
Interview Response: The loop first executes the body, checks the condition, and executes it again while it is truthy.
Code Example:
let i = 0;
do {
alert(i);
i++;
} while (i < 3);
Explain, How the For-Loop works?
View Answer:
Interview Response: The for loop sets a starting point, condition, and steps. The starting point executes once upon entering the loop. The condition gets checked before every loop iteration. The loop body runs again and again while the condition is truthy. If false, the loop terminates.
The general loop algorithm works like this:
Run begin
The general loop algorithm works like this:
Run begin
- (if condition → run body and run step)
- (if condition → run body and run step)
- (if condition → run body and run step)
- ...
Code Example:
// for (let i = 0; i < 3; i++) alert(i)
// run begin
let i = 0;
// if condition → run body and run step
if (i < 3) {
alert(i);
i++;
}
// if condition → run body and run step
if (i < 3) {
alert(i);
i++;
}
// if condition → run body and run step
if (i < 3) {
alert(i);
i++;
}
// ...finish, because now i == 3
What is a For-Loop inline variable declaration?
View Answer:
Interview Response: In simple terms, an inline variable declaration is made inside a for loop, leaving it within the loop's scope.
Technical Response: Inline variable declaration is the process of declaring a variable starting point inside of the for-loop. The variable is only visible inside the loop and cannot be accessed globally.
Code Example:
for (let i = 0; i < 3; i++) {
alert(i); // 0, 1, 2
}
alert(i); // error, no such variable
Code Example: Variable declaration outside of the loop
let i = 0;
for (i = 0; i < 3; i++) {
// use an existing variable
alert(i); // 0, 1, 2
}
alert(i); // 3, visible, because declared outside of the loop
Is it possible to skip or omit parts of the for-loop settings?
View Answer:
Interview Response: We can omit any or all of the parts of the for-loop. If we omit all parts, it results in an endless loop. The semi-colons must remain, or it results in a syntax error.
Technical Response: Yes, it is possible to omit parts or all the for-loop settings. If you remove all the parts, it results in an endless loop. Please note that the two semicolons (;) must be present, and otherwise, there would be a syntax error.
Code Example:
let i = 0; // we have i already declared and assigned
for (; i < 3; i++) {
// no need for "start"
alert(i); // 0, 1, 2
}
Can you stop a loop based on a specific condition?
View Answer:
Interview Response: We can call the break directive to stop the loop based on a specific condition.
Technical Response: Yes, You can achieve this by using the break directive or statement to stop the loop at any time. This approach is ideal for cases when you need to pause the loop in the middle or at various points along its length. The break directive works with all traditional looping structures. (It does not work with forEach).
Code Example: While Loop - Stopping the Loop when a number does not get entered.
let sum = 0;
while (true) {
let value = +prompt('Enter a number', '');
if (!value) break; // (*)
sum += value;
}
alert('Sum: ' + sum);
Code Example: For Loop
let text = '';
for (let i = 0; i < 10; i++) {
if (i === 3) {
break;
}
text += 'The number is ' + i + '<br>';
}
document.getElementById('demo').innerHTML = text;
// Output:
// A loop with a break statement.
// The number is 0
// The number is 1
// The number is 2
How does the continue directive (statement) work in a loop? Does it stop the whole loop?
View Answer:
Interview Response: The continue directive does not stop the whole loop; instead, it stops the current iteration and forces the loop to start a new one if a specific condition exists.
Technical Response: The continue directive is a "lighter version" of the break statement. It does not stop the whole loop; instead, it stops the current iteration and forces the loop to start a new one (if the condition allows).
Code Example: The Loop uses the continue statement to output odd values.
for (let i = 0; i < 10; i++) {
// if true, skip the remaining part of the body
if (i % 2 == 0) continue;
alert(i); // 1, then 3, 5, 7, 9
}
What is the difference between the break statement and the continue directive?
View Answer:
Interview Response: If a specific condition exists, the break statement ends the loop and the continue directive stops the loop and forces to start over.
Technical Response: The break statement stops the loop in the middle or several places of its body. The continue directive is a “lighter version” of break. It does not stop the whole loop; instead, it stops the current iteration and forces the loop to start a new one (if the condition allows).
What is a potential benefit of using the continue directive?
View Answer:
Interview Response: The continue directive helps decrease nesting and increases code readability.
Can the continue or break directives be used with the shorthand ternary (?) expression?
View Answer:
Interview Response: No, You cannot use the continue or break directives in a ternary operator.
Technical Response: No, the continue or break directives on a ternary operator's right side (?) results in a syntax error.
Code Example:
if (i > 5) {
alert(i);
} else {
continue; // continue is allowed here
}
// continue is not allowed on the right side of the question mark operator (?)
(i > 5) ? alert(i) : continue;
How do you break out of two nested for loops?
View Answer:
Interview Response: You can use a label to break out of two nested for loops, and the break directive targets the label to ensure that both loops halt.
Code Example:
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
let input = prompt(`Value at coordinates (${i},${j})`, '');
// if an empty string or canceled, then break out of both loops
if (!input) break outer; // (*)
// do something with the value...
}
}
alert('Done!');
Can labels jump to an arbitrary place in the code?
View Answer:
Interview Response: No, Labels do not allow us to jump into an arbitrary place in the code.
Technical Response: No, Labels do not allow us to jump into an arbitrary place in the code. A call to break/continue is only possible from inside a loop, and the label must be somewhere above the directive.
Code Example:
break label; // doesn't jump to the label below
label: for (...)