Question
How do you write a while loop in JavaScript?
Answer
A while loop repeats a block of code over and over for as long as its condition stays true.
Loops let you repeat work without copying code. A while loop checks a condition before each pass; while it's true, the block runs again:
let i = 0;
let sum = 1;
while (i < 5) {
console.log('sum: ' + sum);
sum = sum + sum;
i = i + 1; // move toward the exit condition!
}
// Output: sum: 1, sum: 2, sum: 4, sum: 8, sum: 16
Every well-behaved loop has three moving parts:
- Initialise the loop variable (
let i = 0) - Check the condition (
i < 5) - Update the loop variable each pass (
i = i + 1)
The most important gotcha is step 3: if you forget to move the loop variable toward the condition becoming false, the condition stays true forever and you get an infinite loop that freezes the page.
while isn't the only loop. JavaScript also has for (compact syntax for counting loops), do-while (runs the body once before checking, so it always executes at least once), and for...in / for...of for stepping through an object's keys or an array's elements.
Note saved — thanks!
Question
How should you handle database errors in Express with MongoDB?
Answer
Wrap every database call in a try/catch, log the real error server-side, and return a generic message with an appropriate HTTP status code.
try {
// insert / update / delete / find
} catch (error) {
console.error(error);
res.status(500).json({
message: 'server error while handling request'
});
}
Security: Never send raw error messages to clients - they may reveal database structure. Log detailed errors server-side, send generic messages to clients.
Note saved — thanks!