JavaScript Loops and Conditionals

JavaScript Loops and Conditionals

To make your JavaScript code do different things based on conditions or repeat tasks, you’ll use conditionals and loops. These are like the decision-making tools and repetitive helpers in programming. Let’s look at how they work.

Conditionals: Making Decisions

Conditionals let your code choose what to do based on whether something is true or false. The most common is the if statement.

The if Statement

Use if to run code only when a condition is true:

let age = 18;

if (age >= 18) {
  console.log('You can vote!');
}

If the condition inside the parentheses is true, the code in the curly braces runs.

else and else if

Add else for what happens when the condition is false:

let age = 16;

if (age >= 18) {
  console.log('You can vote!');
} else {
  console.log('You are too young to vote.');
}

Use else if for multiple conditions:

let score = 85;

if (score >= 90) {
  console.log('Grade: A');
} else if (score >= 80) {
  console.log('Grade: B');
} else if (score >= 70) {
  console.log('Grade: C');
} else {
  console.log('Grade: F');
}

For more on variables and data types, which you often use in conditions, check out JavaScript variables and JavaScript data types.

Comparison Operators

You’ll use these operators in conditions:

  • == (loose equality)
  • === (strict equality)
  • != (not equal)
  • !== (strict not equal)
  • > , < , >= , <=

Be careful with == vs ===. Strict equality checks both value and type. Learn more in the MDN comparison operators guide.

The switch Statement

For many else if conditions checking the same variable, switch can be cleaner:

let day = 'Monday';

switch (day) {
  case 'Monday':
    console.log('Start of the work week');
    break;
  case 'Friday':
    console.log('Almost weekend!');
    break;
  case 'Saturday':
  case 'Sunday':
    console.log('Weekend time');
    break;
  default:
    console.log('Regular day');
}

The break stops the switch from running the next cases. default is like else.

Loops: Repeating Code

Loops run the same code multiple times. Great for working with arrays or doing something a set number of times.

The for Loop

Use for when you know how many times to loop:

for (let i = 0; i < 5; i++) {
  console.log('Count: ' + i);
}
// Outputs: Count: 0, Count: 1, Count: 2, Count: 3, Count: 4

The loop has three parts:

  • Initialization: let i = 0 (runs once at start)
  • Condition: i < 5 (checked before each loop)
  • Increment: i++ (runs after each loop)

The while Loop

Use while when you don’t know how many times, but you know when to stop:

let count = 0;
while (count < 3) {
  console.log('Count: ' + count);
  count++;
}
// Outputs: Count: 0, Count: 1, Count: 2

Be careful with while loops - if the condition never becomes false, you’ll have an infinite loop!

The do...while Loop

Similar to while, but runs the code first, then checks the condition:

let i = 0;
do {
  console.log('Count: ' + i);
  i++;
} while (i < 3);
// Outputs: Count: 0, Count: 1, Count: 2

This guarantees the code runs at least once.

Looping Through Arrays

For arrays, you can use a for loop with the array length:

let fruits = ['apple', 'banana', 'orange'];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// Outputs: apple, banana, orange

Or use forEach for a simpler way:

let fruits = ['apple', 'banana', 'orange'];
fruits.forEach(function(fruit) {
  console.log(fruit);
});
// Outputs: apple, banana, orange

forEach is a method on arrays. Learn more about arrays in JavaScript arrays and objects.

break and continue

In loops, break stops the loop entirely:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i); // Stops at 4
}

continue skips the rest of the current loop and goes to the next:

for (let i = 0; i < 5; i++) {
  if (i === 2) {
    continue;
  }
  console.log(i); // Outputs: 0, 1, 3, 4 (skips 2)
}

Putting It Together

Conditionals and loops often work together. Here’s an example checking numbers in an array:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let evenNumbers = [];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    evenNumbers.push(numbers[i]);
  }
}

console.log(evenNumbers); // Outputs: [2, 4, 6, 8, 10]

Practice with these concepts, and you’ll be able to write more dynamic JavaScript code. For more advanced topics like functions, see JavaScript functions.

The MDN JavaScript Guide has detailed explanations of all these concepts.

Last updated on