JavaScript Loops and Conditionals Guide

javascript
loops
conditionals
advanced

Conditional Statements

if/else Statement

if (score > 90) {
  console.log('A grade');
} else if (score > 80) {
  console.log('B grade');
} else {
  console.log('C grade or below');
}

Switch Statement

const fruit = 'apple';
 
switch (fruit) {
  case 'apple':
    console.log('Red fruit');
    break;
  case 'banana':
    console.log('Yellow fruit');
    break;
  default:
    console.log('Unknown fruit');
}

Ternary Operator

const canVote = age >= 18 ? 'Yes' : 'No';

Loops

for Loop

for (let i = 0; i < 10; i++) {
  console.log(`Count: ${i}`);
}

while Loop

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

do...while Loop

let count = 0;
do {
  console.log(count);
  count++;
} while (count < 3);

Iterating Arrays

const numbers = [1, 2, 3];
 
for (const num of numbers) {
  console.log(num);
}

Advanced Iteration

  • Using forEach, map, filter, and reduce for arrays.
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
 
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 6