While Loops
Like many other languages, JavaScript features a while loop. Instead of relying on an explicit counter variable (like a for loop), it simply evaluates a single boolean expression.
The loop keeps running as long as the condition evaluates to true.
Syntax
let count = 0;
while (count < 3) {
console.log(count);
count++; // Make sure the condition eventually becomes false!
}
Traversal Using While
A classic use case for while loops is traversing deeply nested data structures, like linked lists or hierarchical objects, where you don’t know the exact “length” or “depth” beforehand.
const person = {
name: "Jane",
parent: {
name: "Alice",
parent: {
name: "Lilly",
},
},
};
let currentPerson = person;
// The loop runs as long as currentPerson evaluates to truthy
while (currentPerson) {
console.log(currentPerson.name);
// Move up the tree. If there is no parent, this becomes undefined.
currentPerson = currentPerson.parent;
}
console.log("No more ancestors!");
// Output: Jane, Alice, Lilly, No more ancestors!