While & For Loops - JavaScript Interview
JavaScript Fundamentals: While & For Loops
In Simple terms, what are loops used for in JavaScript?
View Answer:
Can you explain how a while loop works?
View Answer:
let i = 0;
while (i < 3) {
// shows 0, then 1, then 2
console.log(i);
i++;
}
What is the definition of an iteration in a JavaScript loop?
View Answer:
let i = 1;
while (i < 3) {
// shows 1, then 2, then 3
console.log(i);
i++;
}
Does a while loop require an explicit incrementor?
View Answer:
// With Incrementor
let i = 3;
while (i) {
// shows 0, then 1, then 2
console.log(i);
i--; // if the incrementor (i--) is missing then it results in an endless loop.
}
// Without Incrementor
// Here's an example of a while loop without an explicit incrementor:
let items = ['apple', 'banana', 'orange'];
while (items.length > 0) {
console.log(items.pop());
}
// This loop removes and logs each item until the array is empty.
Are curly brackets required in a single-line loop body?
View Answer:
let i = 3;
while (i) console.log(i--);
What is the difference between a Do-While and a While Loop?
View Answer:
do {
// loop body
} while (condition);
Can you explain how the do-while loop works in JavaScript?
View Answer:
let i = 0;
do {
console.log(i);
i++;
} while (i < 3);
How does a for-loop function in JavaScript?
View Answer:
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)
- ...
// for (let i = 0; i < 3; i++) console.log(i)
// run begin
let i = 0;
// if condition → run body and run step
if (i < 3) {
console.log(i);
i++;
}
// if condition → run body and run step
if (i < 3) {
console.log(i);
i++;
}
// if condition → run body and run step
if (i < 3) {
console.log(i);
i++;
}
// ...finish, because now i == 3
What is a for-Loop inline variable declaration?
View Answer:
for (let i = 0; i < 3; i++) {
console.log(i); // 0, 1, 2
}
console.log(i); // error, no such variable
let i = 0;
for (i = 0; i < 3; i++) {
// use an existing variable
console.log(i); // 0, 1, 2
}
console.log(i); // 3, visible, because declared outside of the loop
Is it possible to skip or omit parts of the for-loop settings?
View Answer:
let i = 0; // we have i already declared and assigned
for (; i < 3; i++) {
// no need for "start"
console.log(i); // 0, 1, 2
}
Can you stop a loop based on a specific condition?
View Answer:
let sum = 0;
while (true) {
let value = +prompt('Enter a number', '');
if (!value) break; // (*)
sum += value;
}
console.log('Sum: ' + sum);
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 work in a loop?
View Answer:
for (let i = 0; i < 10; i++) {
// if true, skip the remaining part of the body
if (i % 2 == 0) continue;
console.log(i); // 1, then 3, 5, 7, 9
}
What is the difference between the break statement and the continue directive?
View Answer:
What is a potential benefit of using the continue directive?
View Answer:
Can the continue or break directives be used with the shorthand ternary (?:) expression?
View Answer:
// proper of the continue directive in a conditional
if (i > 5) {
console.log(i);
} else {
continue; // continue is allowed here
}
// continue is not allowed on the right side of the question mark operator (?)
(i > 5) ? console.log(i) : continue;
How do you break out of two nested for loops?
View Answer:
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...
}
}
console.log('Done!');
Can labels jump to an arbitrary place in the code?
View Answer:
break label; // doesn't jump to the label below
label: for (...)
What is the difference between the While and For loops in JavaScript?
View Answer:
What is an infinite loop in JavaScript, and how can it be avoided?
View Answer:
An example of an infinite loop would be:
while (true) {
console.log('This is an infinite loop');
}
This loop will never stop because the condition for the while
loop is always true
.
To avoid an infinite loop, you should always ensure the loop's exit condition will be met. Here is a corrected version of the above code:
let counter = 0;
while (counter < 5) {
console.log('This will not be an infinite loop');
counter++;
}
In this corrected version, the loop will exit after it has run 5 times because counter
will be equal to 5, making the condition counter < 5
false.
What is a nested loop in JavaScript, and why would you use one?
View Answer:
Here's a simple example of a nested loop in JavaScript where we print a multiplication table.
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`${i} * ${j} = ${i * j}`);
}
}
This code will output:
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
In this example, for each iteration of the outer loop (i), the inner loop (j) runs completely, performing the multiplication and logging the result. This gives us the multiplication table for numbers 1 to 3.
How do you create an infinite loop in JavaScript intentionally?
View Answer:
Here's a simple example of intentionally creating an infinite loop in JavaScript:
while (true) {
console.log('This is an intentional infinite loop');
}
Remember, this code will run indefinitely and print 'This is an intentional infinite loop' until you manually stop the execution. For example, in a browser, you might need to close the tab or the entire browser.
Infinite loops should be used with caution, as they can cause your program to become unresponsive and may consume a lot of CPU resources. Always make sure there's a good reason to use them, and they are managed correctly.
This questions is intended to give the interviewee the chance to show whether they have a clear understanding of loop dynamics in programming.