Back to JavaScript
2025-12-035 min read

Decision Making and Loops

Learn Decision Making and Loops step by step with clear examples and exercises.

Why This Matters

Decision Making and Loops are fundamental concepts in programming that enable you to create dynamic, interactive, and complex applications using JavaScript, a versatile language primarily used for web development. By mastering these topics, you can build programs capable of making decisions based on user input or data conditions, repeating specific actions as needed, and handling various scenarios efficiently.

Prerequisites

Before diving into decision making and loops in JavaScript, it's essential to have a good understanding of the following:

  1. Variables and data types
  2. Functions
  3. Arrays
  4. Basic input/output (console.log(), prompt())
  5. Control structures like if statements and conditional operators (e.g., >=, ===)
  6. Understanding basic JavaScript syntax, such as curly braces {}, semicolons ;, and variable declarations using let or const.

Core Concept

Decision Making

If Statements

An if statement in JavaScript allows you to test a condition and execute code if the condition is true. Here's an example:

let age = 20;
if (age >= 18) {
console.log("You are eligible to vote.");
} else if (age < 13) {
console.log("You are a child and cannot vote.");
} else {
console.log("You are a teenager and can't vote yet.");
}

Switch Statements

A switch statement is used when you want to compare a variable with multiple cases. Here's an example:

let grade = 'B';

switch (grade) {
case 'A':
console.log("Excellent!");
break;
case 'B':
console.log("Very good.");
break;
case 'C':
console.log("Good job.");
break;
case 'D':
console.log("You need to study more.");
break;
default:
console.log("Invalid grade.");
}

Loops

For Loop

A for loop is used when you want to repeat a block of code a specific number of times. Here's an example that prints numbers from 1 to 20:

for (let i = 1; i <= 20; i++) {
console.log(i);
}

While Loop

A while loop continues executing as long as a specified condition is true. Here's an example that prints numbers from 1 to 20:

let i = 1;
while (i <= 20) {
console.log(i);
i++;
}

Do-While Loop

A do-while loop executes the code block at least once before checking the condition, unlike a while loop. Here's an example that prompts the user to enter a number and continues until they enter 0:

let num;
do {
num = prompt("Enter a number (or 0 to stop):");
console.log(`You entered: ${num}`);
} while (num !== 0);

Worked Example

Let's create a simple program that calculates the factorial of a number using a for loop.

let num = prompt("Enter a non-negative integer:");
if (num < 0) {
console.log("Invalid input. Please enter a non-negative integer.");
} else {
let fact = 1;
for (let i = 2; i <= num; i++) {
fact *= i;
}
console.log(`Factorial of ${num}: ${fact}`);
}

Common Mistakes

  1. Forgetting to increment the loop counter in a for, while, or do-while loop.
  2. Using = instead of == for comparison in if statements (assignment vs. equality).
  3. Not including a break statement in a switch statement to exit when a case is matched.
  4. Forgetting to declare variables before using them.
  5. Incorrectly using quotation marks for string literals (e.g., "hello" instead of 'hello').
  6. Not properly handling edge cases in decision-making structures, such as checking for null or undefined values.
  7. Using incorrect syntax for control structures, like forgetting to enclose the condition in parentheses for an if statement (e.g., if number > 10 instead of if (number > 10)).
  8. Not properly initializing loop variables before using them in a for, while, or do-while loop.
  9. Forgetting to include the semicolon at the end of a statement, which can lead to unexpected behavior and errors.

Practice Questions

  1. Write a program that checks if a number is even or odd using an if statement.
  2. Create a program that calculates the sum of all numbers in an array using a for loop.
  3. Write a program that finds the largest number in an array using a while loop.
  4. Implement a program that prints the Fibonacci sequence up to a given number using a for loop.
  5. Create a program that asks the user for their age and determines if they are eligible to vote based on their age (18 or older).
  6. Write a program that checks if a given word is a palindrome (reads the same backwards as forwards) using an if statement.
  7. Implement a program that finds the second-largest number in an array using a combination of for, while, and if statements.
  8. Create a program that generates a random number between 1 and 100 using a loop and the Math.random() function.
  9. Write a program that calculates the average of a list of numbers using a for loop and the Array.reduce() method.
  10. Implement a program that finds all prime numbers up to a given number using a combination of for, if, and a helper function.

FAQ

How do I exit a loop early in JavaScript?

You can use the break statement to exit a loop early. For example, in a for loop:

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

How do I create a nested loop in JavaScript?

To create a nested loop in JavaScript, simply place one loop inside another. Here's an example that prints the multiplication table for a given number:

let num = prompt("Enter a number to print its multiplication table:");
for (let i = 1; i <= 10; i++) {
console.log(`${num} x ${i}: ${num * i}`);
}
Decision Making and Loops | JavaScript | XQA Learn