Learn advanced loop types
Runs code first, then checks condition. Runs at least once!
do {
// Code runs first
} while (condition);
Print numbers from 1 to N
let i = 1;
do {
console.log(i);
i++;
} while (i <= n);
Simulates a menu that runs at least once
let choice = 0;
do {
console.log('Menu: 1-Start, 2-Stop, 3-Exit');
choice = getUserChoice();
} while (choice !== 3);
Loop through object properties (keys)
for (let key in object) {
console.log(key + ': ' + object[key]);
}
Display student information using for-in
let student = {
name: 'Ali',
age: 20,
grade: 'A',
city: 'Karachi'
};
for (let key in student) {
console.log(key + ': ' + student[key]);
}
Display product prices using for-in
let products = {
laptop: 50000,
phone: 30000,
tablet: 20000,
watch: 5000
};
for (let item in products) {
console.log(item + ': Rs.' + products[item]);
}
// While - checks first
while (i <= 5) {
console.log(i);
i++;
}
// Do-While - runs first, then checks
do {
console.log(i);
i++;
} while (i <= 5);
// For - loop through numbers
for (let i = 0; i < 5; i++) {
console.log(i);
}
// For-In - loop through object keys
for (let key in object) {
console.log(key);
}