while Loop — JS Technical Interview Questions & Answers
Repeat while a condition stays true.
while Loop
- Repeat while a condition stays true.
- while Loop is JavaScript control flow. if / switch pick a branch. for / while repeat. Condition must be boolean-ish: if (marks >= 40). Use === not =.
- for (let i = 0; i < arr.length; i++) or for (const m of marks). while needs a change inside or it loops forever.
- Trap: = inside if. Trap: off-by-one on the last index.
Technical Interview Tip: while Loop: tiny marks example, predict the path.
Code Examples for while Loop
while Loop — working example
for (let i = 1; i <= 3; i++) {
if (i === 2) continue;
console.log("for", i);
}
let n = 3;
while (n > 0) {
console.log("while", n);
n -= 1;
}
const user = { name: "Ada", city: "Pune" };
for (const key in user) console.log(key, user[key]);
for (const ch of "JS") console.log(ch);while Loop — for/while/do-while repeat work; for...in walks keys; for...of walks iterable values.
How to Explain while Loop to an Interviewer
When while Loop?
To branch or repeat Show one small snippet