const age =20;const category = age >=18?"adult":"minor";console.log(category);// "adult"// Nested (use sparingly)const tier = age >=65?"senior": age >=18?"adult":"minor";
Note Great for simple inline conditions. Avoid deeply nested ternaries -- they quickly become unreadable. Use if/else for complex logic.
const items =["apple","banana","cherry"];for(let i =0; i < items.length; i++){console.log(`${i +1}. ${items[i]}`);}
Output
"1. apple"
"2. banana"
"3. cherry"
Note Classic loop when you need the index. For simple iteration, prefer for...of. Cache .length in the initializer if the array is very large and not changing.
const scores =[88,92,75,100];let sum =0;for(const score of scores){
sum += score;}console.log(`Average: ${sum / scores.length}`);// Works with strings toofor(const char of"hello"){process(char);}
Output
"Average: 88.75"
Note Works on any iterable: arrays, strings, Maps, Sets, generators. Does NOT work on plain objects -- use Object.entries() or for...in for those.
Note Iterates over enumerable string properties, including inherited ones. Avoid for arrays (use for...of). Use Object.hasOwn() to filter inherited keys.
for in looploop object keysiterate propertiesfor in
while and do...while
Syntax
while(condition){...}do{...}while(condition);
Example
// Retry until success (with limit)let attempts =0;let success =false;while(!success && attempts <5){
attempts++;
success =Math.random()>0.7;}console.log(`Succeeded after ${attempts} attempt(s): ${success}`);// do...while always runs at least oncelet input;do{
input =prompt("Enter a number > 10:");}while(Number(input)<=10);
Note do...while guarantees at least one iteration. Useful for retry logic and input validation loops.
break;// exit loopcontinue;// skip to next iteration
Example
const data =[3,-1,7,0,5,-3,9];const positives =[];for(const n of data){if(n <0)continue;// skip negativesif(positives.length>=3)break;// stop after 3
positives.push(n);}console.log(positives);// [3, 7, 5]
Note break exits the innermost loop. Use labeled breaks to exit outer loops: outer: for (...) { for (...) { break outer; } }
const matrix =[[1,2,3],[4,5,6],[7,8,9],];let found =null;
search:for(const row of matrix){for(const cell of row){if(cell ===5){
found = cell;break search;}}}console.log(found);// 5
Note Labels let you break/continue a specific outer loop from inside a nested loop. Rarely needed but invaluable for searching nested structures.