Prompt To Build

Create real apps with AI

Chapter 7: Controlling the Flow - Logic, Conditionals, and Loops

Guiding Your Code: Decisions and Repetition

In programming, it's often necessary to make decisions based on certain conditions or to repeat a set of actions multiple times. Just as Forth uses conditional words and looping constructs to control program execution, JavaScript provides powerful mechanisms for controlling the flow of your code. Understanding these concepts and how to prompt AI to generate them is fundamental to building dynamic and interactive applications.

This chapter will cover conditional statements (if, else if, else, switch) and looping constructs (for, while, do...while, forEach), demonstrating how to use AI to implement logic and repetition in your JavaScript code.

Conditional Statements: Making Decisions

Conditional statements allow your program to execute different blocks of code based on whether a specified condition is true or false.

The if, else if, and else Statements

These are the most common conditional statements, allowing for branching logic.

Prompt:
Write a JavaScript function checkNumber that takes one argument, num.

If num is positive, print "The number is positive."
If num is negative, print "The number is negative."
If num is zero, print "The number is zero."
AI-Generated Code (Expected):
function checkNumber(num) {
  if (num > 0) {
    console.log("The number is positive.");
  } else if (num < 0) {
    console.log("The number is negative.");
  } else {
    console.log("The number is zero.");
  }
}

// Example usage:
// checkNumber(5);   // Output: The number is positive.
// checkNumber(-3);  // Output: The number is negative.
// checkNumber(0);   // Output: The number is zero.
Analysis: The AI correctly uses if, else if, and else to handle three different conditions, demonstrating clear branching logic.

The switch Statement

The switch statement is an alternative to if...else if...else when you have many possible execution paths based on a single variable's value.

Prompt:
Write a JavaScript function getWeekdayName that takes a number day (0 for Sunday, 1 for Monday, etc.) 
and returns the corresponding weekday name. Use a switch statement. 
If the number is not between 0 and 6, return "Invalid day."
AI-Generated Code (Expected):
function getWeekdayName(day) {
  switch (day) {
    case 0:
      return "Sunday";
    case 1:
      return "Monday";
    case 2:
      return "Tuesday";
    case 3:
      return "Wednesday";
    case 4:
      return "Thursday";
    case 5:
      return "Friday";
    case 6:
      return "Saturday";
    default:
      return "Invalid day.";
  }
}

// Example usage:
// console.log(getWeekdayName(3)); // Output: Wednesday
// console.log(getWeekdayName(7)); // Output: Invalid day.
Analysis: The AI correctly implements the switch statement, including the default case for invalid input, which is good practice.

Looping Constructs: Repeating Actions

Loops allow you to execute a block of code repeatedly until a certain condition is met. This is essential for processing lists of data, performing calculations, or generating repetitive content.

The for Loop

The for loop is commonly used when you know exactly how many times you want to repeat a block of code.

Prompt:
Write a JavaScript for loop that prints numbers from 1 to 5 to the console.
AI-Generated Code (Expected):
for (let i = 1; i <= 5; i++) {
  console.log(i);
}

// Expected output:
// 1
// 2
// 3
// 4
// 5
Analysis: The AI generates a standard for loop, correctly setting the initialization, condition, and increment.

The while Loop

The while loop executes a block of code as long as a specified condition is true. It's often used when the number of iterations is not known beforehand.

Prompt:
Write a JavaScript while loop that starts with a variable count initialized to 0. 
The loop should continue as long as count is less than 3. 
Inside the loop, print the current value of count and then increment count by 1.
AI-Generated Code (Expected):
let count = 0;
while (count < 3) {
  console.log(count);
  count++;
}

// Expected output:
// 0
// 1
// 2
Analysis: The AI correctly sets up a while loop, ensuring the count variable is incremented to avoid an infinite loop.

The do...while Loop

The do...while loop is similar to while, but it guarantees that the loop body will execute at least once, because the condition is evaluated after the first iteration.

Prompt:
Write a JavaScript do...while loop that prints "Hello!" to the console once, even if a condition isDone is initially true.
AI-Generated Code (Expected):
let isDone = true;

do {
  console.log("Hello!");
} while (!isDone);

// Expected output:
// Hello!
Analysis: The AI demonstrates the do...while loop's characteristic of executing at least once, regardless of the initial condition.

The for...of Loop (for Iterables)

Introduced in ES6, the for...of loop provides a simpler way to iterate over iterable objects like arrays, strings, Maps, Sets, and more.

Prompt:
Given an array of names: const names = ["Alice", "Bob", "Charlie"];

Write a JavaScript for...of loop to print each name to the console.
AI-Generated Code (Expected):
const names = ["Alice", "Bob", "Charlie"];

for (const name of names) {
  console.log(name);
}

// Expected output:
// Alice
// Bob
// Charlie
Analysis: The AI correctly uses the for...of loop, which is often preferred for its readability when iterating over array elements.

Conclusion: Directing Your Program's Path

Conditional statements and loops are the bedrock of program logic. They allow your JavaScript code to respond dynamically to different situations and efficiently process data. By effectively prompting AI to generate these control flow structures, you gain immense power in directing your program's behavior. In the next chapter, we will delve into the art of refining and debugging AI-generated code.

---

References: Controlling the Flow